HttpURLConnection Post issues - java

I have the following code in my program, used for inserting record -
private Void downloadUrl() throws IOException {
String postParameters;
HttpURLConnection urlConnection = null;
postParameters = "name="+ URLEncoder.encode(user.name,"UTF-8")
+"&age="+URLEncoder.encode(user.age+"","UTF-8")
+"&username="+URLEncoder.encode(user.username,"UTF-8")
+"&password="+URLEncoder.encode(user.password,"UTF-8");
if (postParameters != null) {
Log.i("Post", "POST parameters: " + postParameters);
try {
URL urlToRequest = new URL(SERVER_ADDRESS);
urlConnection = (HttpURLConnection) urlToRequest.openConnection();
urlConnection.setReadTimeout(30000 /* milliseconds */);
urlConnection.setConnectTimeout(30000 /* milliseconds */);
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
urlConnection.setFixedLengthStreamingMode(
postParameters.getBytes().length);
PrintWriter out = new PrintWriter(urlConnection.getOutputStream());
out.print(postParameters.getBytes());
out.close();
// handle issues
int statusCode = urlConnection.getResponseCode();
Log.e("Response", "The response is: " + statusCode);
} catch (MalformedURLException e) {
// handle invalid URL
Log.e("Response", "invalid URL");
} catch (SocketTimeoutException e) {
// hadle timeout
Log.e("Response", "handle timeout");
} catch (IOException e) {
// handle I/0
Log.e("Response", "handle IO problem");
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
}
return null;
}
The code is showing no errors and the logged entries are
09-27 12:24:17.944 5006-5039/? E/Response﹕ The response is: 200
09-27 12:24:33.729 5006-5118/? I/Post﹕ POST parameters: name=vibha&age=25&username=vib&password=1234
But when I check the database, the new record is not created.
But if I use PHP code in a file and post the same parameters,the records are getting inserted.
My requirement for help and guidance is how to pass the post parameter in the HttpURLConnection class

Related

HttpUrlConnection returns -1 status code

I have problem with connecting to my server. Following code returns -1 as response code and null as response message.
protected Boolean doInBackground(MyTaskParams... params) {
URL url = null;
String load = params[0].jobj.toString();
try {
url = new URL(params[0].serverUrl);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setConnectTimeout(3000);
urlConnection.setReadTimeout(3000);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
urlConnection.setChunkedStreamingMode(0);
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.connect();
OutputStreamWriter osw = new OutputStreamWriter(urlConnection.getOutputStream());
osw.write(load);
osw.flush();
osw.close();
if(urlConnection.getResponseCode()==200 && urlConnection.getResponseMessage().contains("true") ) return true;
else return false;
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
While debbuging url and body content (which is load in code) are correct. When I try to connect with the server using those params with Fiddler it works perfectly and I get 200 status code. Do you have any ideas what is wrong?
Im passing jData object as the jobj:
JSONObject User=new JSONObject();
JSONObject Mobile=new JSONObject();
JSONObject jData=new JSONObject();
try {
User.put ("UserLogin", "test");
User.put ("UserPassword", "test");
Mobile.put ("MobileIDD", IDD);
Mobile.put("MobileToken", token);
jData.put("Mobile", Mobile);
jData.put("User", User);
} catch (JSONException e) {
e.printStackTrace();
}
#EDIT
Solution with System.setProperty("http.keepAlive", "false") didnt help.
I solved the problem. It was in this line:
if(urlConnection.getResponseCode()==200 && urlConnection.getResponseMessage().contains("true") ) return true;
When I changed it to:
int code = urlConnection.getResponseCode();
if (code==200.....)
It started working.

Parse.com REST API Error Code 400: Bad Request from Java HTTP Request to Cloud Function

I have a string that I am trying to send to a Parse.com cloud function. According to the REST API documentation (https://www.parse.com/docs/rest#general-requests), it must be in json format, so I made it into a json object and converted it to a string to append to the end of the http request url.
JSONObject jsonParam = new JSONObject();
jsonParam.put("emailId", emailId);
String urlParameters = jsonParam.toString();
Then I send the request as so, in my attempt to match their cURL code example as Java code:
con.setDoOutput(true);
DataOutputStream wr = null;
wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
Nonetheless, I receive a returned error code of 400 with error message "Bad Request", which I believe to be caused by unrecognizable parameters being sent to the cloud function. None of the other errors in my code trigger. Yet I verified through console logs that emailId is a normal string and the resulting JSON object, as well as its .toString() equivalent comes out as a proper string reading of a JSON object. Also this worked for another function I have in which I am creating an object in my Parse database. So why would it not work here?
Here is the full function for reference and context:
private void sendEmailWithParse(String emailId) throws IOException {
String url = "https://api.parse.com/1/functions/sendEmailNow";
URL obj = new URL(url);
HttpsURLConnection con = null;
try {
con = (HttpsURLConnection) obj.openConnection();
} catch (IOException e) {
System.out.println("Failed to connect to http link");
e.printStackTrace();
}
//add request header
try {
con.setRequestMethod("POST");
} catch (ProtocolException e) {
System.out.println("Failed to set to POST");
e.printStackTrace();
}
con.setRequestProperty("X-Parse-Application-Id", "**************************************");
con.setRequestProperty("X-Parse-REST-API-Key", "************************************************");
con.setRequestProperty("Content-Type", "application/json");
JSONObject jsonParam = new JSONObject();
jsonParam.put("emailId", emailId);
System.out.println("parameter being sent to cloud function: " + jsonParam);
System.out.println("parameter being sent to cloud function as string: " + jsonParam.toString());
String urlParameters = jsonParam.toString();
// Send post request
con.setDoOutput(true);
DataOutputStream wr = null;
try {
wr = new DataOutputStream(con.getOutputStream());
} catch (IOException e1) {
System.out.println("Failed to get output stream");
e1.printStackTrace();
}
try {
wr.writeBytes(urlParameters);
} catch (IOException e) {
System.out.println("Failed to connect to send over Parse object as parameter");
e.printStackTrace();
}
try {
wr.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
wr.close();
} catch (IOException e) {
System.out.println("Failed to connect to close datastream connection");
e.printStackTrace();
}
int responseCode = 0;
try {
responseCode = con.getResponseCode();
} catch (IOException e) {
System.out.println("Failed to connect to get response code");
e.printStackTrace();
}
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
System.out.println("Response message: " + con.getResponseMessage());
}
I solved the problem by using the HttpRequest external library. It gave me better control of the request and made for easier debugging of the problem. The server was receiving the request just fine, the problem was with the JSON encoding. Rather than putting the JSON object as a parameter in the request, I inserted it into the body of the http request and encoded it in UTF-8.
In the end, this is the code that worked:
String url = "https://api.parse.com/1/functions/sendEmailNow";
URL obj = new URL(url);
//Attempt to use HttpRequest to send post request to parse cloud
HttpRequest request = HttpRequest.post(obj).contentType("application/json");
request.header("X-Parse-Application-Id", "**************************");
request.header("X-Parse-REST-API-Key", "********************");
JSONObject jsonParam = new JSONObject();
jsonParam.put("emailId", emailId);
request.send(jsonParam.toString().getBytes("UTF8"));
if (request.ok())
System.out.println("HttpRequest WORKED");
else
System.out.println("HttpRequest FAILED " + request.code() + request.body());

FileNotFoundException trying to send JSON to .NET webservice using HttpURLConnection

I am trying to parse a response from an InputStream from a HttpURLConnection using the following code.I get an error when trying to get the InputStream.I am just looking to get a response to check if the web-servcice call worked OK.
static final String SOAP_ACTION="http://888topup.com/ImageProcess.svc/UploadImage";
java.net.URL url=null;
try {
url = new java.net.URL(SOAP_ACTION);
} catch (MalformedURLException e) {
Log.e(TAG, "Bad URL",e);
}
JSONObject obj=new JSONObject();
try {
obj.put("Vaue", value);
} catch (JSONException e) {
Log.e(TAG, "Create JSONObjerct throws an error");
}
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection)url.openConnection();
} catch (IOException e1) {
Log.e(TAG,"Error opening connection",e1);
}
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
try {
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Accept", "*/*");
urlConnection.addRequestProperty("Accept-Encoding", "gzip deflate sdch");
urlConnection.setRequestProperty("Content-Type","application/json");
} catch (ProtocolException e) {
Log.e(TAG,"Error setting header",e);
}
try {
OutputStream os=urlConnection.getOutputStream();
BufferedOutputStream bos=new BufferedOutputStream(os);
byte[] data=obj.toString().getBytes();
bos.write(data);
InputStream is=urlConnection.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String response;
response=br.readLine();
Log.d(TAG, "Response: "+response);
bos.close();
br.close();
is.close();
urlConnection.disconnect();
} catch (IOException e) {
Log.e(TAG,"Error peforming read-write operations",e);
}
Here is the Logcat entry for what happened when I tried to run this code:
MainActivity(9628): Error peforming read-write operations
MainActivity(9628): java.io.FileNotFoundException: http://888topup.com/ImageProcess.svc/UploadImage
MainActivity(9628): at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:186)
MainActivity(8989): at com.example.imageuploadtest.MainActivity.sendStringToServiceUsingRest(MainActivity.java:184)
MainActivity(8989): at com.example.imageuploadtest.MainActivity.access$0(MainActivity.java:149)
MainActivity(8989): at com.example.imageuploadtest.MainActivity$1$1.run(MainActivity.java:66)
EDIT:
The operation as specified in WSDL:
<wsdl:operation name="UploadImage">
<wsdl:input wsaw:Action="http://tempuri.org/IImageProcess/UploadImage" message="tns:IImageProcess_UploadImage_InputMessage"/>
<wsdl:output wsaw:Action="http://tempuri.org/IImageProcess/UploadImageResponse" message="tns:IImageProcess_UploadImage_OutputMessage"/>
</wsdl:operation>
Adding urlConnection.connect() before writing data to the OutputStream does not work either.
EDIT:Using the URL(SOAP_ACTION) and passing jsondata works from Sencha-Touch for someone else who tested it.
Tried passing JSONObject as String instead of byte data.Did not work either?
There were a few mistakes with what I was doing,firstly I was passing the wrong parameter Vaue instead of Value to the service.
JSONObject obj=new JSONObject();
try {
String value_key="Value";
obj.put(value_key, value);
Log.d(TAG,obj.toString());
} catch (JSONException e) {
Log.e(TAG, "Create JSONObjerct throws an error");
}
Secondly,I was trying to parse a response when no response was being sent.So, I replace the code to get the InputStream with the following code:
int response=urlConnection.getResponseCode();
The entire code is here:
java.net.URL url=null;
try {
url = new java.net.URL(SOAP_ACTION);
} catch (MalformedURLException e) {
Log.e(TAG, "Bad URL",e);
}
JSONObject obj=new JSONObject();
try {
String value_key="Value";
obj.put(value_key, value);
Log.d(TAG,obj.toString());
} catch (JSONException e) {
Log.e(TAG, "Create JSONObjerct throws an error");
}
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection)url.openConnection();
} catch (IOException e1) {
Log.e(TAG,"Error opening connection",e1);
}
urlConnection.setDoOutput(true);
try {
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Accept", "*/*");
//urlConnection.addRequestProperty("Accept-Encoding", "gzip deflate sdch");
urlConnection.setRequestProperty("Content-Type","application/json");
} catch (ProtocolException e) {
Log.e(TAG,"Error setting header",e);
}
try {
urlConnection.connect();
DataOutputStream dos=new DataOutputStream(urlConnection.getOutputStream());
dos.write(obj.toString().getBytes());
int response=urlConnection.getResponseCode();
Log.d(TAG, "Response code: "+response);
urlConnection.disconnect();
} catch (IOException e) {
Log.e(TAG,"Error peforming read-write operations",e);
}
And finally I used this to send the data to the web-service as binary data:
DataOutputStream dos=new DataOutputStream(urlConnection.getOutputStream());
dos.write(obj.toString().getBytes());

Android: Checking HTTP response code: getting 200; should be 302

I am checking a website for 302 messages, but I keep receiving 200 in my code:
private class Checker extends AsyncTask<Integer,Void,Integer>{
protected void onPreExecute(){
super.onPreExecute();
//display progressdialog.
}
protected Integer doInBackground(Integer ...code){
try {
URL u = new URL ( "http://www.reddit.com/r/notarealurlinredditqwerty");
HttpURLConnection huc = (HttpURLConnection) u.openConnection();
huc.setRequestMethod("POST");
HttpURLConnection.setFollowRedirects(true);
huc.connect();
code[0] = huc.getResponseCode();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return code[0];
}
protected void onPostExecute(Integer result){
super.onPostExecute(result);
//dismiss progressdialog.
}
}
That is my Async task for checking. Here is the code implementing it:
int code = -1;
Checker checker = new Checker();
try {
code = checker.execute(code).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
Log.d("code:", "" + code);
That log always returns 200, but I know that URL is 302 (it redirects to a search page on reddit.com).
What am I doing wrong?
This line just needs to be set to false:
HttpURLConnection.setFollowRedirects(false);
You can use HttpURLConnection. I have used it for response code in a few applications. I did not encounter any problems.
URL url = new URL("http://yoururl.com");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
int code = connection.getResponseCode();

HttpUrlConnection is freezing my AsyncTask

In the "doInBackground" function of a AsyncTask, I got the following piece of code :
try
{
URL url = new URL(myUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
Authenticator.setDefault(new Authenticator(){
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication ("myUsername", "myPassword".toCharArray());
}
});
conn.connect();
int response = conn.getResponseCode();
inputStream = conn.getInputStream();
String content = convertInputStreamToString(inputStream);
return content;
catch (Exception e) {
e.printStackTrace();
return null;
}
When the credentials are ok, everything works fine and the ResponseCode is 200. But if I put the wrong credentials, getResponseCode() makes the AsyncTask wait for an answer indefinitely (timeout won't work). Looking at HttpUrlConnection object tells me that the ResponseCode is -1.
I need to handle every situation, even if the user provides a bad credential. How can I get an usable answer? Should I use another class than HttpUrlConnection?
Are you returning String back from this function and are you handling exceptions? Did you write onPostExecute?
Here is the code that works perfectly for me:
URL url = new URL(strUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Host", "myhost.com");
conn.setRequestProperty("Authorization", "Basic " + Base64.encodeToString(toencode, Base64.DEFAULT));
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; PPC; en-US; rv:1.3.1)");
conn.setRequestProperty("Accept-Charset", "UTF-8");
conn.setConnectTimeout (5000) ;
conn.setDoOutput(true);
conn.setDoInput(true);
BufferedInputStream in = new BufferedInputStream(conn.getInputStream());
result = Utilities.readStream(in);
status_code = conn.getResponseCode();
return result;
} catch (MalformedURLException e) {
return e.getMessage();
} catch (ProtocolException e) {
try {
status_code = conn.getResponseCode();
} catch (IOException e1) {
status_code = -1;
}
return e.getMessage();
} catch (IOException e) {
try {
status_code = conn.getResponseCode();
} catch (IOException e1) {
status_code = -1;
}
return e.getMessage();
} catch ( Exception e ) {
try {
status_code = conn.getResponseCode();
} catch (IOException e1) {
status_code = -1;
}
return e.getMessage();
}
finally
{
conn = null;
}

Categories

Resources