HttpURLConnection modified to Apache HttpComponents - java

I'm modifying my code to use Apache HttpComponents after I was advised it's a cleaner approach
HttpURLConnection code (working):
String names = "names[]=EndUser/WebTransaction/WebTransaction/JSP/index.jsp";
try (PrintWriter writer = response.getWriter()) {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("X-Api-Key", "myId");
conn.setRequestMethod("GET");
conn.setDoOutput(true);
conn.setDoInput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(names);
wr.flush();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
System.out.println(line);
writer.println(HTML_START + "<h2> NewRelic JSON Response:</h2><h3>" + line + "</h3>" + HTML_END);
}
wr.close();
reader.close();
}catch(MalformedURLException e){
e.printStackTrace();
}
This is my code modified to use Apache HttpComponents(404 not found response):
try (PrintWriter writer = response.getWriter()) {
HttpClient client = HttpClientBuilder.create().build();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("X-Api-Key", "myID"));
nameValuePairs.add(new BasicNameValuePair("names[]", "EndUser/WebTransaction/WebTransaction/JSP/index.jsp"));
HttpGet request1 = new HttpGet(url + URLEncodedUtils.format(nameValuePairs, "utf-8"));
request1.setHeader("Accept", "application/json");
HttpResponse response1 = client.execute(request1);
System.out.println(response1.getStatusLine().getStatusCode());
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(response1.getEntity().getContent()));
while ((line = reader.readLine()) != null) {
System.out.println(line);
writer.println(HTML_START + "<h2> NewRelic JSON Response:</h2><h3>" + line + "</h3>" + HTML_END);
}
reader.close();
}catch(MalformedURLException e){
e.printStackTrace();
}
Could someone point out to me the correct way to accomplish this please.

Much much cleaner approach is to use Retrofit like library, Because these are boilerplate codes.
You can still use this code as a generic method to bring in Json objects so that you can process them and get what ever necessary information you want out of it.But it is not cleaner, It is messy trust me. :)
Since I do not have your actual API url I will try to give an example using this API function.
Retrofit is type safe, which means you specify the model pojo and it will take care of doing necessary casting to the Json object to your model itself which is cool.
model,
public class Application {
private Integer id;
private String name;
private String language;
private String health_status;
//Getters and setters
}
dto,
public class ApplicationListDot {
private List<Application> applications;
}
Interface,
public interface RestController {
#GET("/v2/applications.json")
ApplicationListDot viewApplications();
}

Related

Method for parsing json data from an API

So I have an API project that sends back some JSON data, and depending on which call this data can be formatted in a number of different ways.
Is the correct way to do this to always return data in the same type (like a Collection ) or is to write a method on the non API application using reflection?
Here is my current method for parsing that data, but it won't work if the JSON data doesn't lend itself to being a Collection:
public static Collection<Map> sendPostRequest(String requestURL)
{
StringBuffer jsonString;
try {
URL url = new URL(requestURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
jsonString = new StringBuffer();
String line;
while ((line = br.readLine()) != null) {
jsonString.append(line);
}
br.close();
connection.disconnect();
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
Gson gson = new Gson();
Type collectionType = new TypeToken<Collection<Map>>(){}.getType();
Collection<Map> dataCollection = gson.fromJson(jsonString.toString(), collectionType);
return dataCollection;
}
I hope this questions isn't too open ended, but just need some logistical/best practices help

Querying Data from SUGARCRM

I have SugarCRM trail account. I can able to get Authenticate and get the AccessToken by the following url.
https://xxxxxxx.trial.sugarcrm.eu/rest/v10/oauth2/token
Method : POST
POST Data : postData: { "grant_type":"password", "client_id":"sugar", "client_secret":"", "username":"admin", "password":"Admin123", "platform":"base" }
Code I used to get the AccessToken
public static String getAccessToken() throws JSONException {
HttpURLConnection connection = null;
JSONObject requestBody = new JSONObject();
requestBody.put("grant_type", "password");
requestBody.put("client_id", CLIENT_ID);
requestBody.put("client_secret", CLIENT_SECRET);
requestBody.put("username", USERNAME);
requestBody.put("password", PASSWORD);
requestBody.put("platform", "base");
try {
URL url = new URL(HOST_URL + AUTH_URL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setUseCaches(false);
connection.setDoOutput(true);
connection.connect();
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
out.write(requestBody.toString());
out.close();
int responseCode = connection.getResponseCode();
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
JSONObject jObject = new JSONObject(response.toString());
if(!jObject.has("access_token")){
return null;
}
String accessToken = jObject.getString("access_token");
return accessToken;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
Now I have retrive Leads from CRM using rest API I can not able to find the appropriate method and Url to do the thing.
I can see the list rest of API's from /help but I cant understand what should be my module name and what I have to :record and how do I pass my access token for authentication.
Can anyone please help me?
The module name is simply the module you which to fetch records from, so in your case you'll want to do a GET request to rest/v10/Leads for a list of Leads. If you want to fetch a specific Lead you replace :record with the id of a Lead - for example: GET rest/v10/Leads/LEAD-ID-HERE
SugarCRM's documentation has a lot of relevant information that might not be included in /help plus working examples.
http://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_7.8/Integration/Web_Services/v10/Endpoints/module_GET/
http://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_7.8/Integration/Web_Services/v10/Examples/PHP/How_to_Fetch_Related_Records/
You need to include your retrieved token into an OAuth-Token header for subsequent requests, and then just use the module name as the endpoint i.e. in your case: "rest/v10/Leads" and call the GET method to retrieve them. Try something akin to this:
String token = getAccessToken();
HttpURLConnection connection = null;
try {
URL url = new URL(HOST_URL + "/rest/v10/Leads");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("OAuth-Token", token);
connection.setUseCaches(false);
connection.setDoOutput(true);
connection.connect();
int responseCode = connection.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
JSONObject jObject = new JSONObject(response.toString());
System.out.println(jObject);
} catch (Exception e) {
e.printStackTrace();
}
In the case you want to filter it down to specific id's to cut down on the amount of returned data, you can specify it after the module name i.e. "rest/v10/Leads/{Id}"

how to pass multiple sets of http parameters to access webservices

As i'm working on Nessus scanner, I have to pass parameters to create a scan. the body of the request should be:
{
"uuid": {template_uuid},
"settings": {
"name": {string},
"description": {string},
"emails": {string},
"launch": {string},
"folder_id": {integer},
"policy_id": {integer},
"scanner_id": {integer},
"text_targets": {string}
}
}
currently I'm trying to pass these parameters by means of the below code:
public static void createScan(){
String url = SERVER_URL+"/scans";
String[] paramName = {"uuid", "settings.name","settings.policy_id","settings.text_targets"};
String[] paramVal = {"xxxx", "xxxx", "xxxx","xx.xx.xxx.xxx"};
try {
String token = login();
httpPost(url, paramName, paramVal, token);
} catch (Exception e) {
e.printStackTrace();
}
}
public static String httpPost(String urlStr, String[] paramName, String[] paramVal, String token) throws Exception {
URL url = new URL(urlStr);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setAllowUserInteraction(false);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setConnectTimeout(500000);
conn.setReadTimeout(500000);
conn.setRequestProperty("X-Cookie:", "token=" + token + ";");
if (paramName != null && paramVal != null) {
OutputStream out = conn.getOutputStream();
Writer writer = new OutputStreamWriter(out, "UTF-8");
for (int i = 0; i < paramName.length; i++) {
writer.write(paramName[i]);
writer.write("=");
writer.write(URLEncoder.encode(paramVal[i], "UTF-8"));
writer.write("&");
}
writer.close();
out.close();
}
if (conn.getResponseCode() != 200) {
throw new IOException(conn.getResponseMessage());
}
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
conn.disconnect();
return sb.toString();
}
and currently by running the above code I'm getting:
Response code: 403
java.io.IOException: Unauthorized
please help me to pass these parameters successfully to create a scan in the Nessus
I cant really help you with the issue but you should really consider using jackson or some other xml/json parser since it seems you need to send the data in JSON. Way easier to just pass an object and Jackson parser will convert it to JSON.
More info on: http://jackson.codehaus.org/
Also consider using apache httpclient since its included in android anyway. Way less messy and easier to maintain.

How do i Send POST method with the JSON data (java)?

i need toSend POST method with the JSON data ,Make sure i need to send JSON Object serialized into string. Not the JSON string itself.so how can i implement this using JAVA
public static String sendPostRequest(String postURL) throws Exception{
String responseStr=null;
//make POST request
String jsonContent = "{'name': 'newIndia','columns': [{'name': 'Species','type': 'STRING'}],'description': 'Insect Tracking Information.','isExportable': true}";
//String data = "{\"document\" : {\"_id\": \"" + id+ "\", \"context\":" + context +"}}";
URL url = new URL(postURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(jsonContent.getBytes().length));
connection.setUseCaches(false);
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
writer.write(jsonContent);
writer.close();
responseStr="Response code: "+connection.getResponseCode()+" and mesg:"+connection.getResponseMessage();
System.out.println(connection.getResponseMessage());
InputStream response;
// Check for error , if none store response
if(connection.getResponseCode() == 200){
response = connection.getInputStream();
}else{
response = connection.getErrorStream();
}
InputStreamReader isr = new InputStreamReader(response);
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(isr);
String read = br.readLine();
while(read != null){
sb.append(read);
read = br.readLine();
}
// Print the String
System.out.println(sb.toString());
connection.disconnect();
return responseStr;
}
For more you can see this example.
I would recommend using Jersey REST framework which works great with GAE. Here is a demo.
Using gson, you can POST JSON data to a web-service very easily.
For example:
public class MyData { //var myJsonData = {
private boolean fans = true; // fans:true,
private boolean funds = true; // funds:true
//private String chart = "day"; // }
}
Now send the POJO to a real web-service:
public class Main {
public static void main(String... args) throws Exception {
URL theUrl = new URL("https://robertsspaceindustries.com/api/stats/getCrowdfundStats");
Gson gson = new Gson();
JsonParser jp = new JsonParser();
MyData thedata = new MyData();
HttpsURLConnection urlConnection = (HttpsURLConnection) theUrl.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true); //allow parameters to be sent/appended
DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream());
wr.writeBytes(gson.toJson(thedata)); //convert the POJO to JSON, then to binary.
wr.flush();
wr.close();
urlConnection.connect(); //start request transmission
JsonElement retJson = jp.parse(new InputStreamReader((InputStream) urlConnection.getContent())); //convert the input stream to a json element
System.out.println(retJson.getAsJsonObject());
urlConnection.disconnect(); //end request transmission
}
}
Replies with:
{"success":1,"{"fans":910125,"funds":8410319141},"code":"OK","msg":"OK"}
(Note, the equivalent cURL command at time of writing was) ->
curl 'https://robertsspaceindustries.com/api/stats/getCrowdfundStats' --data-binary '{"fans":true,"funds":true}'

Java: how to use UrlConnection to post request with authorization?

I would like to generate POST request to a server which requires authentication. I tried to use the following method:
private synchronized String CreateNewProductPOST (String urlString, String encodedString, String title, String content, Double price, String tags) {
String data = "product[title]=" + URLEncoder.encode(title) +
"&product[content]=" + URLEncoder.encode(content) +
"&product[price]=" + URLEncoder.encode(price.toString()) +
"&tags=" + tags;
try {
URL url = new URL(urlString);
URLConnection conn;
conn = url.openConnection();
conn.setRequestProperty ("Authorization", "Basic " + encodedString);
conn.setDoOutput(true);
conn.setDoInput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
// Process line...
}
wr.close();
rd.close();
return rd.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
return e.getMessage();
}
catch (IOException e) {
e.printStackTrace();
return e.getMessage();
}
}
but the server doesn't receive the authorization data. The line which is supposed to add authorization data is the following:
conn.setRequestProperty ("Authorization", "Basic " + encodedString);
and the line
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
also throws an IOException.
Anyway I would be very thankful if anyone could suggest any fix of the logic above in order to enable authorization using POST with UrlConnection.
but obviously it doesn't work as it is supposed to although if the same logic is used for GET request everything works fine.
A fine example found here. Powerlord got it right, below, for POST you need HttpURLConnection, instead.
Below is the code to do that,
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setRequestProperty ("Authorization", encodedCredentials);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(data);
writer.flush();
String line;
BufferedReader reader = new BufferedReader(new
InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
writer.close();
reader.close();
Change URLConnection to HttpURLConnection, to make it POST request.
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
Suggestion (...in comments):
You might need to set these properties too,
conn.setRequestProperty( "Content-type", "application/x-www-form-urlencoded");
conn.setRequestProperty( "Accept", "*/*" );
I don't see anywhere in the code where you specify that this is a POST request. Then again, you need a java.net.HttpURLConnection to do that.
In fact, I highly recommend using HttpURLConnection instead of URLConnection, with conn.setRequestMethod("POST"); and see if it still gives you problems.
To do oAuth authentication to external app (INSTAGRAM) Step 3 "get the token after receiving the code" Only code below worked for me
Worth to state also that it worked for me using some localhost URL with a callback servlet configured with name "callback in web.xml and callback URL registered: e.g. localhost:8084/MyAPP/docs/insta/callback
BUT after successfully completed authentication steps, using same external site "INSTAGRAM" to do GET of Tags or MEDIA to retrieve JSON data using initial method didn't work.
Inside my servlet to do GET using url like
e.g. api.instagram.com/v1/tags/MYTAG/media/recent?access_token=MY_TOKEN only method found HERE worked
Thanks to all contributors
URL url = new URL(httpurl);
HashMap<String, String> params = new HashMap<String, String>();
params.put("client_id", id);
params.put("client_secret", secret);
params.put("grant_type", "authorization_code");
params.put("redirect_uri", redirect);
params.put("code", code); // your INSTAGRAM code received
Set set = params.entrySet();
Iterator i = set.iterator();
StringBuilder postData = new StringBuilder();
for (Map.Entry<String, String> param : params.entrySet()) {
if (postData.length() != 0) {
postData.append('&');
}
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.setDoOutput(true);
conn.getOutputStream().write(postDataBytes);
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
builder.append(line).append("\n");
}
reader.close();
conn.disconnect();
System.out.println("INSTAGRAM token returned: "+builder.toString());
To send a POST request call:
connection.setDoOutput(true); // Triggers POST.
If you want to sent text in the request use:
java.io.OutputStreamWriter wr = new java.io.OutputStreamWriter(connection.getOutputStream());
wr.write(textToSend);
wr.flush();
I ran into this problem today and none of the solutions posted here worked. However, the code posted here worked for a POST request:
// HTTP POST request
private void sendPost() throws Exception {
String url = "https://selfsolve.apple.com/wcResults.do";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
}
It turns out that it's not the authorization that's the problem. In my case, it was an encoding problem. The content-type I needed was application/json but from the Java documentation:
static String encode(String s, String enc)
Translates a string into application/x-www-form-urlencoded format using a specific encoding scheme.
The encode function translates the string into application/x-www-form-urlencoded.
Now if you don't set a Content-Type, you may get a 415 Unsupported Media Type error. If you set it to application/json or anything that's not application/x-www-form-urlencoded, you get an IOException. To solve this, simply avoid the encode method.
For this particular scenario, the following should work:
String data = "product[title]=" + title +
"&product[content]=" + content +
"&product[price]=" + price.toString() +
"&tags=" + tags;
Another small piece of information that might be helpful as to why the code breaks when creating the buffered reader is because the POST request actually only gets executed when conn.getInputStream() is called.
On API 22 The Use Of BasicNamevalue Pair is depricated, instead use the HASMAP for that. To know more about the HasMap visit here more on hasmap developer.android
package com.yubraj.sample.datamanager;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import com.yubaraj.sample.utilities.GeneralUtilities;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
/**
* Created by yubraj on 7/30/15.
*/
public class ServerRequestHandler {
private static final String TAG = "Server Request";
OnServerRequestComplete listener;
public ServerRequestHandler (){
}
public void doServerRequest(HashMap<String, String> parameters, String url, int requestType, OnServerRequestComplete listener){
debug("ServerRequest", "server request called, url = " + url);
if(listener != null){
this.listener = listener;
}
try {
new BackgroundDataSync(getPostDataString(parameters), url, requestType).execute();
debug(TAG , " asnyc task called");
} catch (Exception e) {
e.printStackTrace();
}
}
public void doServerRequest(HashMap<String, String> parameters, String url, int requestType){
doServerRequest(parameters, url, requestType, null);
}
public interface OnServerRequestComplete{
void onSucess(Bundle bundle);
void onFailed(int status_code, String mesage, String url);
}
public void setOnServerRequestCompleteListener(OnServerRequestComplete listener){
this.listener = listener;
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
class BackgroundDataSync extends AsyncTask<String, Void , String>{
String params;
String mUrl;
int request_type;
public BackgroundDataSync(String params, String url, int request_type){
this.mUrl = url;
this.params = params;
this.request_type = request_type;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... urls) {
debug(TAG, "in Background, urls = " + urls.length);
HttpURLConnection connection;
debug(TAG, "in Background, url = " + mUrl);
String response = "";
switch (request_type) {
case 1:
try {
connection = iniitializeHTTPConnection(mUrl, "POST");
OutputStream os = connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(params);
writer.flush();
writer.close();
os.close();
int responseCode = connection.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
/* String line;
BufferedReader br=new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line=br.readLine()) != null) {
response+=line;
}*/
response = getDataFromInputStream(new InputStreamReader(connection.getInputStream()));
} else {
response = "";
}
} catch (IOException e) {
e.printStackTrace();
}
break;
case 0:
connection = iniitializeHTTPConnection(mUrl, "GET");
try {
if (connection.getResponseCode() == connection.HTTP_OK) {
response = getDataFromInputStream(new InputStreamReader(connection.getInputStream()));
}
} catch (Exception e) {
e.printStackTrace();
response = "";
}
break;
}
return response;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if(TextUtils.isEmpty(s) || s.length() == 0){
listener.onFailed(DbConstants.NOT_FOUND, "Data not found", mUrl);
}
else{
Bundle bundle = new Bundle();
bundle.putInt(DbConstants.STATUS_CODE, DbConstants.HTTP_OK);
bundle.putString(DbConstants.RESPONSE, s);
bundle.putString(DbConstants.URL, mUrl);
listener.onSucess(bundle);
}
//System.out.println("Data Obtained = " + s);
}
private HttpURLConnection iniitializeHTTPConnection(String url, String requestType) {
try {
debug("ServerRequest", "url = " + url + "requestType = " + requestType);
URL link = new URL(url);
HttpURLConnection conn = (HttpURLConnection) link.openConnection();
conn.setRequestMethod(requestType);
conn.setDoInput(true);
conn.setDoOutput(true);
return conn;
}
catch(Exception e){
e.printStackTrace();
}
return null;
}
}
private String getDataFromInputStream(InputStreamReader reader){
String line;
String response = "";
try {
BufferedReader br = new BufferedReader(reader);
while ((line = br.readLine()) != null) {
response += line;
debug("ServerRequest", "response length = " + response.length());
}
}
catch (Exception e){
e.printStackTrace();
}
return response;
}
private void debug(String tag, String string) {
Log.d(tag, string);
}
}
and Just call the function when you needed to get the data from server either by post or get like this
HashMap<String, String>params = new HashMap<String, String>();
params.put("action", "request_sample");
params.put("name", uname);
params.put("message", umsg);
params.put("email", getEmailofUser());
params.put("type", "bio");
dq.doServerRequest(params, "your_url", DbConstants.METHOD_POST);
dq.setOnServerRequestCompleteListener(new ServerRequestHandler.OnServerRequestComplete() {
#Override
public void onSucess(Bundle bundle) {
debug("data", bundle.getString(DbConstants.RESPONSE));
}
#Override
public void onFailed(int status_code, String mesage, String url) {
debug("sample", mesage);
}
});
Now it is complete.Enjoy!!! Comment it if find any problem.
HTTP authorization does not differ between GET and POST requests, so I would first assume that something else is wrong. Instead of setting the Authorization header directly, I would suggest using the java.net.Authorization class, but I am not sure if it solves your problem. Perhaps your server is somehow configured to require a different authorization scheme than "basic" for post requests?
i was looking information about how to do a POST request. I need to specify that mi request is a POST request because, i'm working with RESTful web services that only uses POST methods, and if the request isn't post, when i try to do the request i receive an HTTP error 405. I assure that my code isn't wrong doing the next: I create a method in my web service that is called through GET request and i point my application to consume that web service method and it works.
My code is the next:
URL server = null;
URLConnection conexion = null;
BufferedReader reader = null;
server = new URL("http://localhost:8089/myApp/resources/webService");
conexion = server.openConnection();
reader = new BufferedReader(new InputStreamReader(server.openStream()));
System.out.println(reader.readLine());

Categories

Resources