I am trying to upload a document from my local machine to Http using following code but I am getting HTTP 400 Bad request error. My source data is in Json.
URL url = null;
boolean success = false;
try {
FileInputStream fstream;
#SuppressWarnings("resource")
BufferedReader bufferedReader = new BufferedReader(new FileReader("C:\\Users\\Desktop\\test.txt"));
StringBuffer buffer = new StringBuffer();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
buffer.append(line);
}
String request = "http://example.com";
URL url1 = new URL(request);
HttpURLConnection connection = (HttpURLConnection) url1.openConnection();
connection.setDoOutput(true); // want to send
connection.setRequestMethod("POST");
connection.setAllowUserInteraction(false); // no user interaction
connection.setRequestProperty("Content-Type", "application/json");
DataOutputStream wr = new DataOutputStream(
connection.getOutputStream());
wr.flush();
wr.close();
connection.disconnect();
System.out.println(connection.getHeaderFields().toString());
// System.out.println(response.toString());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Have a look into apache http libraries which will help a lot with that:
File file = new File("path/to/your/file.txt");
try {
HttpClient client = new DefaultHttpClient();
String postURL = "http://someposturl.com";
HttpPost post = new HttpPost(postURL);
FileBody bin = new FileBody(file);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("myFile", bin);
post.setEntity(reqEntity);
HttpResponse response = client.execute(post);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
Log.i("RESPONSE",EntityUtils.toString(resEntity));
}
} catch (Exception e) {
e.printStackTrace();
}
The example above is taken from my blog and it should work with standard Java SE as well as Android.
The DataOutputStream is for writing primitive types. This causes it to add extra data to the stream. Why aren't you just flushing the connection?
connection.getOutputStream().flush();
connection.getOutputStream().close();
EDIT:
It also occurs to me that you've not actually written any of your post data, so you probably want a something more like:
OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
wr.write(buffer.toString());
wr.close();
Related
i need to call a service get using http connection, the response contains arabic characters, but when i call it using the code below
try {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
InputStream in = new BufferedInputStream(conn.getInputStream());
response = IOUtils.toString(in, "UTF-8");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
the reponse is
1|U|����� ������|$2|L|���� �������|$3|S|����
I tried another solution not using Commons-io but also not working
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setConnectTimeout(5000);
connection.setRequestMethod("GET");
connection.connect();
int statusCode = connection.getResponseCode();
//Log.e("statusCode", "" + statusCode);
if (statusCode == 200) {
sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
char[] tmp = new char[1024];
int l;
while((l = reader.read(tmp)) != -1) {
sb.append(tmp, 0, l);
}
//sb = buffer.toString();
}
connection.disconnect();
if (sb != null)
serverResponse = sb.toString();
Do i need to change anything from web service??? but when i call it from browser all characters show clearly with no problem
any suggestion?
Maybe the server is not using UTF-8, your code is trying to use UTF-8 to decode the data but that will only work if the server is using the same encoding.
The browser works because maybe it is using the HTTP header "Content-Encoding" which should indicate the encoding used for the data.
Please decode your string response
String dateStr = URLDecoder.decode(yourStringResponse, "utf-8");
I have a code written in java for android app. by using HttpPost and DefaultHttpClient library. Currently, i am recoding it to replace the HttpPost and DefaultHttpClient library with HttpURLConnection, as DefaultHttpClient has been depricated.
I have done it for one my project, and it worked.
But in the current project I am not getting same response from the webservice upon using HttpURLConnection instead of DefaultHttpClient. Would any one help me please where I'm doing mistake?
Here is the old code:
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
String postParameter = "Param1=" + Value1 + "&Param2="+ Value2+ "&Param3="+Value3;
try {
httpPost.setEntity(new StringEntity(postParameter));
} catch (Exception e) {
e.printStackTrace();
}
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
And here is my new code
_Url = new URL(Url);
HttpURLConnection urlconnection = (HttpURLConnection) _Url.openConnection();
urlconnection.setRequestMethod(Type);
urlconnection.setConnectTimeout(Timeout);
urlconnection.setUseCaches(false);
urlconnection.setDoInput(true);
urlconnection.setDoOutput(true);
String postParameter = "Param1=" + Value1 + "&Param2="+ Value2+ "&Param3="+Value3;
BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(os));
writer.write(postParameter);
writer.flush();
writer.close();
os.close();
urlconnection.connect();
The code is running without any error, but the webservice is not giving same response as it is giving for the old code.
You are not getting the input stream, try the below code
try {
String postParameter = "Param1=" + Value1 + "&Param2="+ Value2+ "&Param3="+Value3;
URL url = new URL(UrlStr);
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Accept",
"application/json");
urlConnection.setRequestProperty("Content-Type",
"application/json");// setting your headers its a json in my case set your appropriate header
urlConnection.setDoOutput(true);
urlConnection.connect();// setting your connection
OutputStream os = null;
os = new BufferedOutputStream(
urlConnection.getOutputStream());
os.write(postParameter.toString().getBytes());
os.flush();// writing your data which you post
StringBuffer buffer = new StringBuffer();
InputStream is = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(
new InputStreamReader(is));
String line = null;
while ((line = br.readLine()) != null)
buffer.append(line + "\r\n");
// reading your response
is.close();
urlConnection.disconnect();// close your connection
return buffer.toString();
} catch (Exception e) {
}
try this
List nameValuePairs = new ArrayList(3);
nameValuePairs.add(new BasicNameValuePair("Param1", value1));
nameValuePairs.add(new BasicNameValuePair("Param2", value2));
nameValuePairs.add(new BasicNameValuePair("Param3", value3));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nameValuePairs);
OutputStream post = request.getOutputStream();
entity.writeTo(post);
post.flush();
I'm trying to make a post to a node.js server but for some reason the body is always empty for me no matter what I try.
I'm testing now towards requestb.in and its always empty there too.
This is the code I use for posting:
public static String post(String url, String json) {
StringBuilder stringBuffer = new StringBuilder();
BufferedReader bufferedReader = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost("http://requestb.in/14a9s7m1");
StringEntity se = new StringEntity("{'string':'string'}", HTTP.UTF_8);
se.setContentType("application/json; charset=UTF-8");
httpPost.setEntity(se);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
httpPost.setHeader("hmac", Methods.getMethods().getHmac(json));
HttpResponse httpResponse = httpClient.execute(httpPost, localContext);
InputStream inputStream = httpResponse.getEntity().getContent();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String readLine = bufferedReader.readLine();
while (readLine != null) {
stringBuffer.append(readLine);
stringBuffer.append("\n");
readLine = bufferedReader.readLine();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return stringBuffer.toString();
}
This is the requestb.in http://requestb.in/14a9s7m1?inspect
raw body should contain the json string, right?
Any suggestions?
You can make many mistakes when using HttpUrlConnection. I admit that I don't see any error, but this doesn't mean anything.
Since Google doesn't recommend using HttpClient and AndroidHttpClient (except for FROYO or older), but we should use HttpUrlConnection instead, you're on the right way (from a Android perspective).
When using a very lightweight wrapper for HttpUrlConnection called DavidWebb, the code looks like this (I left out hmac-generation):
public class TestWebbRequestBin {
#Test public void stackOverflow20543115() throws Exception {
Webb webb = Webb.create();
webb.setBaseUri("http://requestb.in");
JSONObject jsonObject = new JSONObject();
jsonObject.put("string", "string");
String json = jsonObject.toString(); // {"string":"string"}
Response<String> response = webb
.post("/1g7afwn1")
.header("Accept", "application/json")
.header("Content-type", "application/json")
.header("hmac", "some-hmac-just-a-test")
.body(json)
.asString();
assertEquals(200, response.getStatusCode());
assertTrue(response.isSuccess());
String body = response.getBody();
assertEquals("ok\n", body);
}
}
When the JSON I post looks like in your example, requestb.in does accept it:
json = "{'string':'string'}";
But this is not valid JSON (here tested in node.js):
> JSON.parse("{'string':'string'}")
SyntaxError: Unexpected token '
at Object.parse (native)
at repl:1:7
at REPLServer.self.eval (repl.js:110:21)
at Interface.<anonymous> (repl.js:239:12)
tl;dr
Take care to send valid JSON
Master HttpUrlConnection or use a simple abstraction library
For nasty bugs you could either debug your node.js code (or console.log(req)) or use a tool like Wireshark.
Try this code to send the string.... In HttpPost you should use key value pairs to send the data.
HttpPost httppost = new HttpPost(SERVER_URL);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("REQUEST", req));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
HttpResponse response = httpclient.execute(httppost);
I am not sure is this the problems. Can you give a tried?
You are sending invalid JSON format string. This make server unable to accept your invalid json string so your body is empty. To solve this, change following code.
StringEntity se = new StringEntity("{\"string\":\"string\"}", HTTP.UTF_8);
I couldn't get HttpPost to work, but HttpUrlConnection works instead. It solves my problem, but doesn't solve the mysterious no body thing of httpPost.
Here is my solution:
public static String post(String ur2l, String json) {
StringBuilder stringBuffer = new StringBuilder();
BufferedReader bufferedReader = null;
try {
URL url = new URL(ur2l);
HttpURLConnection conn;
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-type", "application/json");
conn.setRequestProperty("hmac", Methods.getMethods().getHmac(json));
conn.setDoOutput(true);
OutputStream os = null;
try {
os = conn.getOutputStream();
os.write(json.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
os.close();
conn.connect();
int respCode = conn.getResponseCode();
if (respCode == 200) {
InputStream inputStream = conn.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String readLine = bufferedReader.readLine();
while (readLine != null) {
stringBuffer.append(readLine);
stringBuffer.append("\n");
readLine = bufferedReader.readLine();
}
}
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return stringBuffer.toString();
}
I am having problems calling a simple JSON web service from an Android app. The .execute() completes successfully with an 200-OK Status however I am unable to read any JSON output or text.
For the record, if I HttpPost a regular webpage, like Google.com, I can read and parse all the markup. Also, I am able to call the complete urlWithParams string from the device's browser and I see JSON output in the browser. This works in device's browser:
http://maps.googleapis.com/maps/api/distancematrix/json?origins=Seattle&destinations=San+Francisco&mode=bicycling&language=fr-FR&sensor=false
When the code runs, the reader is always blank and reader.readLine() never runs. Returns an empty string. If I change the URL to Google.com, it works and returns 17,000 characters. Thanks!
protected String doInBackground(String... uri) {
String responseString = null;
try {
//String urlGoogle = "http://google.com";
//String urlWithParams = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=Seattle&destinations=San+Francisco&mode=bicycling&language=fr-FR&sensor=false";
String urlOnly = "http://maps.googleapis.com/maps/api/distancematrix/json";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(urlOnly);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("origins", "Seattle"));
nameValuePairs.add(new BasicNameValuePair("destinations", "Cleveland"));
nameValuePairs.add(new BasicNameValuePair("sensor", "false"));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httpPost);
int status = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append((line + "\n"));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
responseString = sb.toString();
}}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return responseString;
}
Maybe you should test other mime types instead of application/json.
1 - Check in your manifest file having INTENET Permission or not.
2 - Use this code its returning data
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
try {
String inputLine;
while ((inputLine = reader.readLine()) != null) {
responseString += inputLine;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Solved! The blank return when calling the JSON page was due to not having the proxy settings defined. Proxy settings were setup on the device however per this post, HttpClient does NOT inherit them.
Adding the following line resolved my issue. The code is now returning JSON.
HttpHost proxy = new HttpHost("172.21.31.239", 8080);
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
I am writing an Android program that needs to access a URL with GET variables which will be logged into a database. All I need to do is open a URL so the web server will log the data! How should I go about this?
Thanks
// default HTTP Client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Use this.
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("URL HERE"));
startActivity(browserIntent);
Hope this helps.
EDIT:
Ok, use this. It calls the URL without opening a browser
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet("URL HERE");
HttpResponse response = httpClient.execute(httpGet, localContext);
You can also use HttpUrlConnection. Sample code -
// Given a URL, establishes an HttpUrlConnection and retrieves
// the web page content as a InputStream, which it returns as
// a string.
private String downloadUrl(String myurl) throws IOException {
InputStream is = null;
// Only display the first 500 characters of the retrieved
// web page content.
int len = 500;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
int response = conn.getResponseCode();
Log.d(DEBUG_TAG, "The response is: " + response);
is = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = readIt(is, len);
return contentAsString;
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (is != null) {
is.close();
}
}
}
// Reads an InputStream and converts it to a String.
public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}
And obviously since it is a netowork call you cannot do it in main/UI thread. So you can do it in async task. More details and Source