Android HttpURLConnection with json string - java

I want to call the following URL:
http://192.168.0.196:8080/openapi/localuser/set?{"syskey":"1234","usrname":"256","usrpwd":"556"}
Use this address to add a new user to the database. To do this I use HttpURLConnection in my AsyncTask class
try {
URL myUrl = new URL(params[0]);
HttpURLConnection conn = (HttpURLConnection) myUrl.openConnection();
conn.setReadTimeout(10000 );
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
// Starts the query
conn.connect();
int response = conn.getResponseCode();
Log.d("lab", "The response is: " + response);
statusMap.put("addUser", Integer.toString(response));
Log.d("lab", "URL: " + params[0]);
}catch (Exception e){
Log.d("lab", "Error2: " + e.getMessage());
}
params[0] = http://192.168.0.196:8080/openapi/localuser/set?{"syskey":"1234","usrname":"256","usrpwd":"556"}
Unfortunately, this call is not working. I do not get the error.
catch returns null

Try like this way. You need to add few line in your code.
public JSONObject makeHttpRequest(String requestURL, JSONObject register) {
try {
url = new URL(requestURL);
connection = (HttpURLConnection) url.openConnection();
connection.setReadTimeout(150000);
connection.setConnectTimeout(150000);
connection.setAllowUserInteraction(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept-Charset", "UTF-8");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
connection.setFixedLengthStreamingMode(register.toString().getBytes().length);
connection.setDoInput(true);
connection.setDoOutput(true);
OutputStreamWriter outputStream = new OutputStreamWriter(connection.getOutputStream());
outputStream.write(register.toString());
outputStream.flush();
Log.e("URL", connection.getURL().toString());
Log.e("JSONObject", register.toString());
} catch (Exception e) {
Log.e("MAIN Exception", e.toString());
}
try {
int statuscode = connection.getResponseCode();
if (statuscode == HttpURLConnection.HTTP_OK) {
is = connection.getInputStream();
} else {
}
} catch (IOException e) {
Log.e("IOException", e.toString());
}
try {
rd = new BufferedReader(new InputStreamReader(is));
response = new StringBuffer();
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\n');
}
Log.e("Response", response.toString() + " ");
rd.close();
} catch (IOException e) {
Log.e("BUFFER_READER", e.toString());
} catch (NullPointerException e) {
Log.e("NullPointerException", e.toString());
} finally {
connection.disconnect();
}
try {
return new JSONObject(response.toString());
} catch (JSONException e) {
Log.e("JSONException", e.toString());
}
return null;
}
Also You are using localHost you must have emulator which can connect to localhost. Unless it will not going to work on any device.

try this :
private String post(String url) throws JSONException {
JSONObject json = new JSONObject();
try {
String query = "";
String EQ = ":";
String AMP = "&";
for (NameValuePair param : parameters) {
query = json.put(param.getName(), param.getValue()) + ",";
}
// url+= "?" + query;
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
if (parameters != null) {
StringEntity se = new StringEntity(query.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
post.setEntity(se);
Log.d("POSTQuery", url + parameters);
}
HttpResponse response = client.execute(post);
StatusLine statusLine = response.getStatusLine();
Log.d("Status Code", "" + statusLine.getStatusCode());
if (statusLine.getStatusCode() == 200) {
return StringifyResponse(response);
}
Log.d("POSTQuery", url);
// Log.d("response", response.toString());
return StringifyResponse(response);
} catch (ClientProtocolException e) {
} catch (IOException e) {
Log.d("response", e.toString());
return "IOException";
}
return null;
}

You need to format all url querystring and then use outputwriter to flush the data :
// Create data variable for sent values to server
String data = URLEncoder.encode("syskey", "UTF-8")
+ "=" + URLEncoder.encode("1234", "UTF-8");
data += "&" + URLEncoder.encode("usrname", "UTF-8") + "="
+ URLEncoder.encode("256", "UTF-8");
data += "&" + URLEncoder.encode("usrpwd", "UTF-8")
+ "=" + URLEncoder.encode("556", "UTF-8");
and then flush the data:
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( data );
wr.flush();
Link here :
http://androidexample.com/How_To_Make_HTTP_POST_Request_To_Server_-_Android_Example/index.php?view=article_discription&aid=64&aaid=89

Related

Getting response code 400 when trying to get access token from Azure AD

I am implementing azure for my web application and trying to get access token by following there openId connect tutorial
https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-protocols-oauth-code
And when i am requesting to get the access token, i am always getting bad request 400
Request to get access token :
POST /{tenant}/oauth2/token HTTP/1.1
Host: https://login.microsoftonline.com
Content-Type: application/x-www-form-urlencoded
grant_type=authorization_code
&client_id=2d4d11a2-f814-46a7-890a-274a72a7309e
&code=AwABAAAAvPM1KaPl.......
&redirect_uri=https%3A%2F%2Flocalhost%2Fmyapp%2F
&resource=https%3A%2F%2Fservice.contoso.com%2F
&client_secret=p#ssw0rd
here is my code :
public static String post( String endpoint,
Map<String, String> params) {//YD
StringBuffer paramString = new StringBuffer("");
//if(!Utilities.checkInternetConnection(context)){
// return XMLHandler.getXMLForErrorCode(context, JSONHandler.ERROR_CODE_INTERNET_CONNECTION);
//}
Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
StringBuffer tempBuffer = new StringBuffer("");
String paramval;
while (iterator.hasNext()) {
Entry<String, String> param = iterator.next();
if (param != null) {
if (paramString.length() > 0) {
paramString.append("&");
}
System.out.println( "post key : " + param.getKey());
String value;
try {
paramval = param.getValue();
if(paramval!=null)
value = URLEncoder.encode(paramval, "UTF-8");
else
value = "";
} catch (UnsupportedEncodingException e) {
value = "";
e.printStackTrace();
}
paramString.append(param.getKey()).append("=")
.append(value);
}
}
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(endpoint);
String data = "";
try {
// Add your data
// httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs))
//httppost.addHeader("Host", host);
httppost.addHeader("Content-Type",
"application/x-www-form-urlencoded");
if (!paramString.equals("")) {
if (tempBuffer.length() > 0) {
data = data + tempBuffer.toString();
}
data = data + paramString.toString();
if (data.endsWith("&")) {
data = data.substring(0, data.length() - 1);
}
httppost.setEntity(new ByteArrayEntity(data.getBytes()));
}
System.out.println( "post Stringbuffer : " + data);
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
int statuscode = response.getStatusLine().getStatusCode();
System.out.println("Response code : " + statuscode);
if (statuscode != 200) {
return null;
}
HttpEntity entity = response.getEntity();
InputStream in = null;
if (entity != null) {
in = entity.getContent();
}
if (in != null) {
StringBuilder builder = new StringBuilder();
String line;
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(in, "UTF-8"));
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} finally {
in.close();
}
String response2 = builder.toString();
System.out.println("response :" + response2);
retrycount = 0;
return response2;
}
}
catch(UnknownHostException e){
e.printStackTrace();
return null;
}
catch (EOFException eof) {
if (retrycount < max_retry) {
eof.printStackTrace();
post( endpoint, params);
retrycount = 1;
}
} catch (Throwable th) {
throw new IOException("Error in posting :" + th.getMessage());
}
retrycount = 0;
return null;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
Please help me with this
Thanks in Advance
Have you ensured the redirect uri passed to /token is the same as the one you passed to /authorize
I believe, it will help if you can test the OAuth auth code flow with your current client id, secret and scope using Postman tool in order to rule out bad configuration.
Please refer to the code below to request AuthorizationCode.
public static void getAuthorizationCode() throws IOException {
String encoding = "UTF-8";
String params = "client_id=" + clientId
+ "&response_type=" + reponseType
+ "&redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F"
+ "&response_mode=query"
+ "&resource=https%3A%2F%2Fgraph.windows.net"
+ "&state=12345";
String path = "https://login.microsoftonline.com/" + tenantId + "/oauth2/authorize";
byte[] data = params.getBytes(encoding);
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(data.length));
conn.setConnectTimeout(5 * 1000);
OutputStream outStream = conn.getOutputStream();
outStream.write(data);
outStream.flush();
outStream.close();
System.out.println(conn.getResponseCode());
System.out.println(conn.getResponseMessage());
BufferedReader br = null;
if (conn.getResponseCode() != 200) {
br = new BufferedReader(new InputStreamReader((conn.getErrorStream())));
} else {
br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
}
System.out.println("Response body : " + br.readLine());
}
Then you could get access token using the AuthorizationCode you got and get refresh code using the code below.
public static void getToken(String refreshToken) throws IOException {
String encoding = "UTF-8";
String params = "client_id=" + clientId + "&refresh_token=" + refreshToken
+ "&grant_type=refresh_token&resource=https%3A%2F%2Fgraph.windows.net";
String path = "https://login.microsoftonline.com/" + tenantId + "/oauth2/token";
byte[] data = params.getBytes(encoding);
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(data.length));
conn.setConnectTimeout(5 * 1000);
OutputStream outStream = conn.getOutputStream();
outStream.write(data);
outStream.flush();
outStream.close();
System.out.println(conn.getResponseCode());
System.out.println(conn.getResponseMessage());
BufferedReader br = null;
if (conn.getResponseCode() != 200) {
br = new BufferedReader(new InputStreamReader((conn.getErrorStream())));
} else {
br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
}
System.out.println("Response body : " + br.readLine());
}
Hope it helps you.

HttpUrlConnection sometimes gives EOF exception

I am using HttpUrlConnection and using POST method to get some data from web server. Sometimes, I get the response and at times I get EOFexception
These are the solutions are I have already tried :
1) System.setProperty("http.keepAlive", "false");
2) if (Build.VERSION.SDK != null && Build.VERSION.SDK_INT > 13) {
connection.setRequestProperty("Connection", "close");
}
Below is my code from AsyncTask class;
CODE :
#Override
protected JSONObject doInBackground(KeyValuePair... keyValuePairs) {
JSONObject jsonResponse = new JSONObject();
HttpURLConnection connection = null;
// check if is Internet is available before making a network call
if (isInternetAvailable()) {
try {
jsonResponse = new JSONObject();
URL url = new URL(urlStr);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setUseCaches(false);
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "UTF-8");
if (Build.VERSION.SDK != null && Build.VERSION.SDK_INT > 13) {
connection.setRequestProperty("Connection", "close");
}
// setting post params
StringBuilder builder = new StringBuilder();
for (int i = 0; i < keyValuePairs.length; i++) {
builder.append(URLEncoder.encode(keyValuePairs[i].getKey(), "UTF-8") + "=" + URLEncoder.encode(keyValuePairs[i].getValue(), "UTF-8") + "&");
GeneralUtils.print("key : " + keyValuePairs[i].getKey() + ", value : " + keyValuePairs[i].getValue());
}
String postData = builder.toString();
postData = postData.substring(0, postData.length() - 1);
GeneralUtils.print("postData " + postData);
byte[] postDataByteArr = postData.getBytes();
connection.setFixedLengthStreamingMode(postDataByteArr.length);
connection.setConnectTimeout(20000);
DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());
dataOutputStream.writeBytes(postData);
dataOutputStream.flush();
dataOutputStream.close();
GeneralUtils.print("respCode " + connection.getResponseCode());
// if connection was not successful
if (connection.getResponseCode() != 200) {
jsonResponse.put("status", "Failure");
jsonResponse.put("message", "Something went wrong. Please Try Again");
} else {
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
String response = sb.toString();
GeneralUtils.print("NetworkCall Server response " + response);
jsonResponse = new JSONObject(response);
}
} catch (JSONException e) {
GeneralUtils.print("NetworkCall.JSONEx 162 " + e);
} catch (MalformedURLException e) {
GeneralUtils.print("NetworkCall.MalformedURLEx " + e);
} catch (IOException e) {
try {
jsonResponse.put("status", "No Internet Connection");
jsonResponse.put("message", "Please check your Internet connection and try again");
} catch (JSONException e1) {
GeneralUtils.print("NetworkCall.JSONEx " + e);
}
} finally {
connection.disconnect();
}
} else {
// if Internet is not available
try {
jsonResponse.put("status", "No Internet Connection");
jsonResponse.put("message", "Please check your Internet connection and try again");
} catch (JSONException e) {
e.printStackTrace();
}
}
return jsonResponse;
}
Many many thanks in advance!
As of now I am following a workaround posted here
which essentially dictates trying to connect N number of times to bypass the EOF exception issue.
In my case, when I catch EOFException, I call the doInBackground again depending upon the reconnectCount;
CODE :
catch (IOException e) {
try {
if (reConnectCount <= 10) {
reConnectCount++;
jsonResponse = doInBackground(keyValuePairs);
} else {
jsonResponse.put("status", "No Internet Connection");
jsonResponse.put("message", "Please check your Internet connection and try again");
}
} catch (JSONException e1) {
GeneralUtils.print("NetworkCall.JSONEx " + e);
}
}
Where jsonResponse essentially holds server response in JSON form. So, whenever doInBackground is successfully executed (i.e. does not get Caught and returns jsonResponse), we overwrite the calling doInBackground's jsonResponse object.

Java - Put Request

I'm trying to perform a "PUT" but nothing happens, i don't catch any exception either.
Here is what I've tried:
String destinationUrl = 'http://stash.myDomain.com/rest/api/1.0/projects/myProj/permissions/users?name=myUser&permission=PROJECT_WRITE';
URL url = null;
try {
url = new URL(destinationUrl)
} catch (MalformedURLException exception) {
exception.printStackTrace();
}
HttpURLConnection httpURLConnection = null;
DataOutputStream dataOutputStream = null;
try {
String userpass = STASH_USERNAME + ":" + STASH_PASSWORD;
String basicAuth = "Basic " + converter.printBase64Binary(userpass.getBytes());
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("PUT");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestProperty("Authorization", basicAuth)
//httpURLConnection.setRequestProperty("Content-Type", "application/json");
dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
dataOutputStream.writeBytes("Hello");
} catch (IOException excepption) {
excepption.printStackTrace();
} finally {
if (dataOutputStream != null) {
try {
dataOutputStream.flush();
dataOutputStream.close();
} catch (IOException exception) {
exception.printStackTrace();
}
}
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
Any idea what should i do ?

Error 86 This method requires a GET or HEAD using Bearer token on Twitter Rest API 1.1 using Java in AppEngine

I have my bearerToken and userID as per Twitter instructions https://dev.twitter.com/docs/auth/application-only-auth and I want t get a list of followers.
I'm getting error 86, which isn't on the list of error codes https://dev.twitter.com/docs/error-codes-responses
Any pointers would be appreciated.
public String getTwitterFriends(String userID, String bearerToken) {
// Use App Bearer token to get public friends
String answer = "";
String param = "count=5000&cursor=-1&user_id=" + userID;
HttpURLConnection connection = null;
try {
// String request =
// "https://api.twitter.com:443/1.1/friends/ids.json?" + param;
String request = "https://api.twitter.com/1.1/friends/ids.json?"
+ param;
URL url = new URL(request);
connection = (HttpURLConnection) url.openConnection();
System.setProperty("http.keepAlive", false ? "true" : "false");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("GET");
// connection.setRequestProperty("Host", "api.twitter.com" +
// ":443");
connection.setRequestProperty("Host", "api.twitter.com");
connection.setRequestProperty("Accept", "*/*");
connection.setRequestProperty("Authorization", "Bearer "
+ bearerToken);
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=utf-8");
connection.setRequestProperty("User-Agent", "UnhappyChappy");
// connection.setRequestProperty("Accept-Encoding", "gzip");
// connection.setRequestProperty("Content-Length", "" +
// Integer.toString(param.getBytes().length));
connection.setUseCaches(false);
DataOutputStream wr = new DataOutputStream(
connection.getOutputStream());
// wr.writeBytes(param);
wr.flush();
wr.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
StringBuilder str = new StringBuilder();
while ((line = reader.readLine()) != null) {
System.out.println(line);
str.append(line);
}
reader.close();
connection.disconnect();
answer = str.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(answer);
return answer;
}
It was the way I issued the GET. I had to go to a lower level on App Engine and use FetchOptions This worked for me, hopefully it will help someone else.
URL url = new URL(request);
HTTPRequest req = new HTTPRequest(url, HTTPMethod.GET);
req.addHeader(new HTTPHeader("Authorization", "Bearer " + bearerToken));
HTTPResponse response = URLFetchServiceFactory.getURLFetchService().fetch(req);
System.out.println(new String(response.getContent()));

my android application get connection time out while the browser still can use

code:
public static String openUrl(String url, String method,
RequestParam params) throws NuageException {
HttpURLConnection conn = null;
String response = "";
String decodParam = params.decod();
if (method.equals(GET))
{
url = url + "?" + decodParam;
// Log.v(LOG_TAG, "GET:" + url);
}
try {
Log.v("开始请求:", String.valueOf(System.currentTimeMillis()));
conn = (HttpURLConnection) new URL(url).openConnection();
conn.setReadTimeout(READTIMEOUT);
conn.setConnectTimeout(CONNECTTIMEOUT);
conn.setUseCaches(false);
conn.setRequestProperty("Connection", "Keep-Alive");
if (method.equals(POST)) {
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.getOutputStream().write(decodParam.getBytes("UTF-8"));
// Log.v(LOG_TAG, "POST:" + url + " " + decodParam);
}
InputStream is = null;
conn.connect();
int responseCode = conn.getResponseCode();
if (responseCode == 200 || responseCode == 201
|| responseCode == 202) {
is = conn.getInputStream();
} else {
is = conn.getErrorStream();
}
response = read(is);
Log.v("请求结束:", String.valueOf(System.currentTimeMillis()));
Log.v(LOG_TAG, "response:" + response);
checkResponse(response);
} catch (MalformedURLException e) {
throw new NuageException(e);
} catch (IOException e) {
if (e.getMessage() != null && e.getMessage().equals(
"Received authentication challenge is null"))
throw new NuageException(new NuageError(
NuageError.ERROR_SESSIONKEY_INVALID, "", "", ""));
e.printStackTrace();
throw new NuageException(e);
} catch (NuageException e) {
throw e;
} finally {
if (conn != null) {
conn.disconnect();
}
}
return response;
}
sometimes i get java.net.SocketTimeoutException: Connection timed out while the browser still work.
anyone can help to improve my code?

Categories