I've a server and a client. My server sends a HttpResponse in a text format. I'm able to receive the text at client. I need to convert back the text to HttpResponse object. Are there any opensource libraries or in-built java/Android mechanisms to do this?
All I've got is converting HttpResponse to text.
Try this way
ByteArrayOutputStream baos = new ByteArrayOutputStream();
response.getEntity().writeTo(baos);
byte[] bytes = baos.getBytes();
Then you could add the content to another HttpResponse object as follows:
HttpResponse response = httpClient.execute(new HttpGet(URL));
response.setEntity(new ByteArrayEntity(bytes));
Just do this using Apache Commons IO: http://commons.apache.org/proper/commons-io/
private byte[] receiveByteArrayData(HttpURLConnection httpURLConnection)
throws IOException
{
return IOUtils.toByteArray(httpURLConnection.getInputStream());
}
Sending byte[] data:
URL url = new URL("http://your.url.here:yourPortNumber/something");
HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
httpUrlConnection.setDoInput(true);
httpUrlConnection.setDoOutput(true);
httpUrlConnection.setRequestProperty("Content-Type", "application/octet-stream");
httpUrlConnection.setRequestMethod("POST");
httpUrlConnection.setFixedLengthStreamingMode(bytes.length);
httpUrlConnection.connect();
httpUrlConnection.getOutputStream().write(bytes);
httpUrlConnection.getOutputStream().flush();
if (httpsUrlConnection.getResponseCode() == 200) //OK
{
System.out.println("successfully uploaded data");
}
httpUrlConnection.disconnect();
I got exactly what I want from
parse http response bytes in java
Thanks everyone for responses :)
Related
I want to add header "Content-Type" "application/json". But I am not been able to do this due to api 23 in android.
OutputStream os= null;
os=httpclient.getOutputStream();
BufferedWriter bw= new BufferedWriter(new OutputStreamWriter(os));
JSONObject jsonobj = new JSONObject();
jsonobj.put("Name","alpha");
jsonobj.put("Status","Active");
jsonobj.put("Type","Admin");
jsonobj.put("Address","beta");
jsonobj.put("Password","333");
jsonobj.put("PhoneNumber",123);
bw.write(jsonobj.toString());
os.close();
I assume that you are trying to make a network call to some API which expects you to add Headers to the HTTP calls you are making and the content-type data is JSON.
If that is your case then you would have to specify the Headers to the instance to respective class with which you are trying to connect..
for example if you are using HttpURLConnection
then it would look like this
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestMethod("POST"); // hear you are telling that it is a POST request, which can be changed into "PUT", "GET", "DELETE" etc.
httpURLConnection.setRequestProperty("Content-Type", "application/json"); // here you are setting the `Content-Type` for the data you are sending which is `application/json`
httpURLConnection.connect();
and when you are posting some data to the instance of the HttpURLConnection you can do it like this...
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("para_1", "arg_1");
jsonObject.addProperty("para_2", "arg_2");
DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
wr.writeBytes(jsonObject.toString());
wr.flush();
wr.close();
I'm trying to send notification for both Android & iOS using non-Latin charset.
I notice when I send message from Android to iOS using non-Latin charset, message displayed on iPhone as "????", since the Java server side for iOS and Android are the same, I assume the problem is how I send the request from Android handset, notice message from iOS to iOS works fine.
below is the code that I'm using to open network connection and sending the request, please, let me know if it's OK.
byte[] bytes = body.getBytes(/*"UTF-16"*//*"ISO-8859-1"*/"UTF-8");
HttpURLConnection conn = null;
StringBuilder stringBuilder = new StringBuilder();
try {
conn = (HttpURLConnection) url.openConnection();//conn.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setFixedLengthStreamingMode(bytes.length);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
// post the request
OutputStream out = conn.getOutputStream();
out.write(bytes);
out.close();
// handle the response
int status = conn.getResponseCode();
if (status != 200) {
Log.d("send message", "Coud Send Message, No Internet Connection Avilable.");
throw new IOException("Post failed with error code " + status);
}
InputStream in = new BufferedInputStream(conn.getInputStream());
// readStream(in);
int b;
while ((b = in.read()) != -1) {
stringBuilder.append((char) b);
}
check below code it works for me, i have also same issue,
to get Data from server,
String is = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
// httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs2));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs2,
HTTP.UTF_8));
HttpResponse responce = httpclient.execute(httppost);
HttpEntity entity = responce.getEntity();
is = EntityUtils.toString(entity, "UTF-8");
} catch (Exception e) {
// TODO: handle exception
Log.d("call http :", e.getMessage().toString());
is = null;
}
return is;
hope it may help you.
Context: In Android, when I use Java's HttpURLConnection object as shown below, I see the POST body correctly on the server side. However, when I use what I believe is the equivalent HttpClient code, the POST body is empty.
Question:
What am I missing?
Server-side is a Django-python server. I have set up a debug point at the entry point of this endpoint but the post body is already empty. How can I debug through it to find out why the body is null?
Note: I already looked at this , but the solution does not work for me.
Code: using HttpURLConnection - this works:
try {
URL url = new URL("http://10.0.2.2:8000/accounts/signup/");
String charset = "UTF-8";
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty ("Authorization", "Basic base64encodedstring==");
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded; charset=" + charset);
connection.setDoInput(true);
StringBuilder sb = new StringBuilder();
sb.append("appver=6&user=value1pw=&hash=h1");
OutputStreamWriter outputWriter = new
OutputStreamWriter(connection.getOutputStream());
outputWriter.write(sb.toString());
outputWriter.flush();
outputWriter.close();
// handle response
} catch () {
// handle this
}
============================================================
Code: using Apache httpclient - does NOT work - server gets empty POST body:
HttpPost mHttpPost = new HttpPost(""http://10.0.2.2:8000/accounts/signup/"");
mHttpPost.addHeader("Authorization", "Basic base64encodedstring==");
mHttpPost.addHeader("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
mHttpPost.addHeader("Accept-Charset", "UTF-8");
String str = "appver=6&user=value1pw=&hash=h1"; // same as the above
StringEntity strEntity = new StringEntity(str);
mHttpPost.setEntity(strEntity);
HttpUriRequest pHttpUriRequest = mHttpPost;
DefaultHttpClient client = new DefaultHttpClient();
httpResponse = client.execute(pHttpUriRequest);
// more code
I figured the reason why this was happening:
The authorization header in the POST request had an extra new line character "\n" - this was causing the request to go through to the server side handler, but with the body getting cut off. I have never noticed this behavior before.
I want to send my id & password to server and get the response from server. Here is my code. It is not working for the first time. But iam getting the response from server if i execute my application on second time. It is throwing "Post method failed: -1 null" on first time. Where iam wrong?? Why if() block is executing on first time?? could you please tell me.
HttpsURLConnection con = null;
String httpsURL = "https://www.abc.com/login";
String query = "id=xyz&password=pqr";
URL url = new URL(httpsURL);
con = (HttpsURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-length", String.valueOf(query.length()));
con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
con.setRequestProperty("User-Agent","Mozilla/4.0(compatible; MSIE 5.0; Windows 98; DigExt)");
con.setDoInput(true);
con.setDoOutput(true);
DataOutputStream output = new DataOutputStream(con.getOutputStream());
output.writeBytes(query);
output.close();
int respCode = con.getResponseCode();
if (respCode != HttpsURLConnection.HTTP_OK)
{
throw new Exception("POST method failed: " + con.getResponseCode()+ "\t" + con.getResponseMessage()); }
else {
//read the content from server
}
1/ It is recommanded to use apache HttpClient rather than URLConnection (see http://developer.android.com/reference/org/apache/http/impl/client/DefaultHttpClient.html)
2/ for login and password, why not use Http Authentication ? both basic and digest are supported by android.
3/ as for you problem, you don't close the underlying outputStream.
you should do:
OutputStream os = con.getOutputStream();
DataOutputStream output = new DataOutputStream(os);
output.writeBytes(query);
output.close();
os.close();
Check Server service validity with other technology and/or classic java. You didn say in your question if you succeed to discriminate the server from the issue.
from java doc ...getResponseCode returns -1 if no code can be discerned from the response (i.e., the response is not valid HTTP).
Java https post request example : http://www.java-samples.com/java/POST-toHTTPS-url-free-java-sample-program.htm
try to close your outputstream after querying the status and not before...that may help
Here is how you should send POST requests in Android
HttpPost httpGet = new HttpPost(server + "/login?email="+username+"&password="+password);
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(httpGet);
You can read response using:
response.getEntity().getContent()
I am able to do a POST of a parameters string. I use the following code:
String parameters = "firstname=john&lastname=doe";
URL url = new URL("http://www.mywebsite.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
connection.setRequestMethod("POST");
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write(parameters);
out.flush();
out.close();
connection.disconnect();
However, I need to do a POST of binary data (which is in form of byte[]).
Not sure how to change the above code to implement it.
Could anyone please help me with this?
Take a look here
Sending POST data in Android
But use ByteArrayEntity.
byte[] content = ...
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new ByteArrayEntity(content));
HttpResponse response = httpClient.execute(httpPost);
You could base-64 encode your data first. Take a look at the aptly named Base64 class.
These links might be helpful:
Android httpclient file upload data corruption and timeout issues
http://getablogger.blogspot.com/2008/01/android-how-to-post-file-to-php-server.html
http://forum.springsource.org/showthread.php?108546-How-do-I-post-a-byte-array