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();
Related
I have the following class that return an spefic field from json response.
The method to request here is with post. How can i do it with get method?
Also i want to make the get request with headers
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost post = new HttpPost(
"");
post.addHeader("Auth-Token", authenticationValues.getAuthToken());
post.addHeader("device-id", authenticationValues.getDeviceId());
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("task", "savemodel"));
String generatedJSONString = null;
params.add(new BasicNameValuePair("code", generatedJSONString));
CloseableHttpResponse response = null;
Scanner in = null;
try {
post.setEntity(new UrlEncodedFormEntity(params));
response = httpClient.execute(post);
HttpEntity entity = response.getEntity();
in = new Scanner(entity.getContent());
while (in.hasNext()) {
JsonString += in.next();
}
EntityUtils.consume(entity);
} catch (IOException e) {
e.printStackTrace();
}
// System.out.println(JsonString);
JSONObject jsonObject = new JSONObject(JsonString);
JSONObject myResponse = jsonObject.getJSONObject("login");
Object myResponse2 = myResponse.get("loginStatus");
System.out.println(myResponse2);
Try this...
URL url = new URL("http://"...);
HttpURLConnection http = (HttpURLConnection)
url.openConnection();
http.setRequestMethod("GET");
http.setDoOutput(true);
http.connect();
OutputStream out = http.getOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(out);
writer.write(FOO);
writer.flush();
writer.close();
InputStreamReader in = new InputStreamReader(http.getInputStream());
BufferedReader br = new BufferedReader(in);
char[] chars = new char[BUF_SIZE];
int size = br.read(chars);
String response = new String(chars).substring(0, size);
All enclosed in a try-catch block.
Some commands like HttpClient or HttpPost are not working. Could anyone help me?
#Override
protected users doInBackground(Void... params){
Map<String, String> dataToSend = new HashMap<>();
dataToSend.put("x", users.x + "");
dataToSend.put("y", users.y);
URL url = new URL(SERVER_ADRESS);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
HttpParams httpRequestPramas = new BasicHttpParams();
conn.setConnectionTimeout(httpRequestPramas, CONNECTION_TIME);
HttpConnectionParams.setSoTimeout(httpRequestPramas, CONNECTION_TIME);
HttpClient client = new DefaultHttpClient(httpRequestPramas);
HttpPost post = new HttpPost(SERVER_ADRESS + "login.php");
users returnedusers = null;
try {
post.setEntity(new UrlEncodedFormEntity(dataToSend));
HttpResponse httpResponse = client.execute(post);
HttpEntity entity = httpResponse.getEntity();
String result = EntityUtils.toString(entity);
JSONObject jObject = new JSONObject(result);
if (jObject.length() == 0){
users = null;
}else{
String vorname = jObject.getString("y");
int kundennummer = jObject.getInt("x");
returnedusers = new users(users.y, users.x);
}
}catch (Exception e){
e.printStackTrace();
}
return returnedusers;
}
Thanks for the help.
Try this way
URL url = new URL("http://example.sitedemo.service.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
Uri.Builder builder = new Uri.Builder().appendQueryParameter("username", "maven")
.appendQueryParameter("password", "123");
String query = builder.build().getEncodedQuery();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
InputStream in = new BufferedInputStream(conn.getInputStream());
response = IOUtils.toString(in, "UTF-8");
ref- android.net.Uri.Builder
Background
I have the following functions, both do the same thing that is POST to a php page:
private void parse(String myurl) throws IOException {
java.util.Date date= new java.util.Date();
Timestamp timestamp = (new Timestamp(date.getTime()));
try {
JSONObject parameters = new JSONObject();
parameters.put("timestamp",timestamp);
parameters.put("jsonArray", new JSONArray(Arrays.asList(makeJSON())));
parameters.put("type", "Android");
parameters.put("mail", mail);
//System.out.println("PARAMS"+parameters.toString());
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// conn.setReadTimeout(10000 /* milliseconds */);
// conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestProperty( "Content-Type", "application/json" );
conn.setDoOutput(true);
conn.setRequestMethod("POST");
OutputStream out = new BufferedOutputStream(conn.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
writer.write(parameters.toString());
writer.close();
out.close();
int responseCode = conn.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
}catch (Exception exception) {
System.out.println("Exception: "+exception);
}
}
In the above I am only sending a single string to the php server at:
writer.write(parameters.toString());
Now I have this function:
InputStream ins = null;
String result = null;
public void postJSON(String url){
DefaultHttpClient http = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost(url);
httppost.setHeader("Accept", "application/json");
httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");
try{
JSONArray json = (makeJSON());
// System.out.println("Arrays"+Arrays.asList(json).toString());
// System.out.println(("simple"+json));
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("timestamp", "t"));
nameValuePairs.add(new BasicNameValuePair("mail", "t"));
nameValuePairs.add(new BasicNameValuePair("type", "t"));
nameValuePairs.add(new BasicNameValuePair("jsonArray", Arrays.asList(json).toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse resp = http.execute(httppost);
HttpEntity entity = resp.getEntity();
ins = entity.getContent();
BufferedReader bufread = new BufferedReader(new InputStreamReader(ins, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while((line = bufread.readLine()) != null){
sb.append(line +"\n");
}
result = sb.toString();
System.out.println(result);
/* if(result.equalsIgnoreCase("There is no update in database")){
}else{
// System.out.println(result);
readAndParseJSON(result);
} */
}catch (Exception e){
// System.out.println("Error: "+e);
}finally{
try{
if(ins != null){
ins.close();
}
}catch(Exception smash){
System.out.println("Squish: "+smash);
}
}
// return result;
}
In the above I am sending name value pairs which I can fetch at the php side based on their names.
As HttpUrlConnection is the suggested way to go in for Android how can I modify the first function to cater for name value pairs. I tried looking online but it just confuses me.
I am also very confused at this line:
conn.setRequestProperty( "Content-Type", "application/json" );
What does the above infer?
and these two:
httppost.setHeader("Accept", "application/json");
httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");
Fiends, i sending JSON String with three parameters to java web service method. but on java side method cant print in console. Please guide me what i have to change from below code?
String json = "";
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
HttpConnectionParams.setSoTimeout(httpParams, 10000);
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpPost httpPost = new HttpPost(url);
HttpGet httpGet = new HttpGet(url);
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("name", "ghanshyam");
jsonObject.put("country", "India");
jsonObject.put("twitter", "ghahhd");
json = jsonObject.toString();
StringEntity se = new StringEntity(json);
se.setContentEncoding("UTF-8");
se.setContentType("application/json");
// 6. set httpPost Entity
System.out.println(json);
httpPost.setEntity(se);
httpGet.se
// 7. Set some headers to inform server about the type of the content
//httpPost.addHeader( "SOAPAction", "application/json" );
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
//String s = doGet(url).toString();
Toast.makeText(getApplicationContext(), "Data Sent", Toast.LENGTH_SHORT).show();
Use the following code to post the json to Java web-service: and get the resopnse as a string.
JSONObject json = new JSONObject();
json.put("name", "ghanshyam");
json.put("country", "India");
json.put("twitter", "ghahhd");
HttpPost post = new HttpPost(url);
post.setHeader("Content-type", "application/json");
post.setEntity(new StringEntity(json.toString(), "UTF-8"));
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse httpresponse = client.execute(post);
HttpEntity entity = httpresponse.getEntity();
InputStream stream = entity.getContent();
String result = convertStreamToString(stream);
and Your convertStremToString() method will be as follows:
public static String convertStreamToString(InputStream is)
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
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();
}
}
return sb.toString();
}
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();