HttP Post method is not working - java

I am trying to use this method i also tried to impot libriries but all in vain. Kindly help me. Not any HTTPClient library is showing on my andriod studio. Help would be appreciated
public String getHttpPost(String url,ContentValues) {
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = client.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Status OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
str.append(line);
}
} else {
Log.e("Log", "Failed to download result..");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str.toString();
}

Oh!Still you are using HttpClient.You can use HttpURLConnection,Volley etc. HttpClient class is now deprecated.Also add Internet permission, and dependensies in gradle file.
HttpURLConnection urlConnection = null;
try {
URL urlToRequest = new URL(_url);
urlConnection = (HttpURLConnection) urlToRequest.openConnection();
urlConnection.setConnectTimeout(30000);
urlConnection.setReadTimeout(30000);
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
if (_authenticationKey != null) {
urlConnection.setRequestProperty(_authenticationKey, _authenticationValue);
}
if (_jsonPacket != null) {
OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
wr.write(_jsonPacket);
wr.flush();
}
int statusCode = urlConnection.getResponseCode();
JSONObject job;
if (statusCode != HttpURLConnection.HTTP_OK) {
InputStream in = new BufferedInputStream(urlConnection.getErrorStream());
String responseString = getResponseString(in);
if (isJSONValid(responseString)) {
job = new JSONObject(responseString);
return new PostingResult(job, Constants.IntegerConstants.failureFromWebService, "");
} else {
return new PostingResult(null, statusCode, Constants.StringConstants.serverCommunicationFailed + "Response code = " + statusCode);
}
} else {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
String responseString = getResponseString(in);
if (isJSONValid(responseString)) {
job = new JSONObject(responseString);
return new PostingResult(job, Constants.IntegerConstants.success, "");
} else {
return new PostingResult(null, statusCode, Constants.StringConstants.serverCommunicationFailed + Constants.StringConstants.serverReadingResponseFailed);
}
}

You can use "Volley" library to make network call.
eg.
Add this line in build.gradle (Module:app)
compile 'com.mcxiaoke.volley:library:1.0.19'
As you are making network call you need internet permission. So add Internet permission line in Manifest.xml
Now you need to write a small method inside your class where you need to make network call and need to pass Hashmap to it. Hashmap contains all your post parameters.
private void getJSONResponse(HashMap<String, String> map, String url) {
pd.show();
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, new JSONObject(map), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Mayur", "Response : " + response);
//tv_res.setText(response.toString());
//pd.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Error Occured", Toast.LENGTH_SHORT).show();
//tv_res.setText("ERROR");
//pd.dismiss();
}
});
request.setRetryPolicy(new DefaultRetryPolicy(20000,DefaultRetryPolicy.DEFAULT_MAX_RETRIES,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));Volley.newRequestQueue(this).add(request);}
Now in your onCreate method or any other method just create a Hashmap of post parameters and pass it to this method with post url.
eg.
HashMap<String, String> map = new HashMap<String, String>();
map.put("fname", "Mayur");
map.put("lname", "Thakur");
getJSONResponse(map,<your url>);

Related

how do i enable httpclient in android studios?

Help! How do i enable the following httpclient in my android studios? Can't seem to find NameValuePair, BasicNameValuePair, Httpclient, Httppost and apparently my HTTPConnectionParams are depracated? How do i resolve them?
ArrayList<NameValuePair> dataToSend = new ArrayList<>();
dataToSend.add(new BasicNameValuePair("name",user.name));
dataToSend.add(new BasicNameValuePair("email",user.email));
dataToSend.add(new BasicNameValuePair("password",user.password));
HttpParams httpRequestParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT);
HttpClient client = new DefaultHttpClient(httpRequestParams);
HttpPost post = new HttpPost(SERVER_ADDRESS + "Register.php");
try{
post.setEntity(new UrlEncodedFormEntity(dataToSend));
client.execute(post);
}catch (Exception e) {
e.printStackTrace();
}
I assume you may be using sdk 23+, try to use URLConnection or downgrade to sdk 22.
I recently had to change almost all of my code because that library has been deprecated. I believe we have been advised to use the original Java net library from now on.
Try the following
try{
URL url = new URL(SERVER_ADDRESS + "Register.php");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setConnectTimeout(CONNECTION_TIMEOUT);
String postData = URLEncoder.encode("name","UTF-8")
+"="+URLEncoder.encode(user.name,"UTF-8");
postData += "&"+URLEncoder.encode("email","UTF-8")
+"="+URLEncoder.encode(user.email,"UTF-8");
postData += "&"+URLEncoder.encode("password","UTF-8")
+"="+URLEncoder.encode(user.password,"UTF-8");
OutputStreamWriter outputStreamWriter = new
OutputStreamWriter(connection.getOutputStream());
outputStreamWriter.write(postData);
outputStreamWriter.flush();
outputStreamWriter.close();
}catch(IOException e){
e.printStackTrace();
}
Hope it helps
BasicNameValuePair is also deprecated. Use HashMap to send keys and values.
HashMap documentation: http://developer.android.com/reference/java/util/HashMap.html
Use this method in order to post data to the "yourFiles.php".
public String performPostCall(String requestURL, HashMap<String, String> postDataParams) {
URL url;
String response = "";
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode=conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line=br.readLine()) != null) {
response+=line;
}
}
else {
response="";
throw new HttpException(responseCode+"");
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
private String getPostDataString(Map<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
You can also use the Volley Library from google to get your job done.
Example of using the library:
RequestQueue queue = Volley.newRequestQueue(activity);
StringRequest strRequest = new StringRequest(Request.Method.POST, "Your URL",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
VolleyLog.d("Home_Fragment", "Error: " + response);
Toast.makeText(activity, "Success", Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(getApplicationContext(), "Error: " + error.getMessage());
Toast.makeText(activity, error.toString(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("name", user.name);
params.put("email", user.email;
params.put("password", user.password);
return params;
}
};
queue.add(strRequest);
);

HttpClient.excute(HttpPost) no response

I constructed an HttpClient, and set timeout parameters.
the code is like this:
while(bufferedinputstream.read()!=-1){
post.setEntity(multipartEntity);
HttpResponse response = httpClient.excute(post);
}
it worked fine for the first several request, and then somehow the response is not returned, and no exception or timeout exception was thrown. Anyone has any idea what's happening?
since you re not getting any errors or exceptions (do you print them out?), you could check the satusCode of your response. Maybe it helps.
(overridden method from my AsyncTask)
protected String doInBackground(String... arg) {
String url = arg[0]; // Added this line
//...
Log.i(DEBUG_TAG, "URL CALL -> " + url);
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
String mResponse = "";
try {
List<NameValuePair> params = new LinkedList<NameValuePair>();
//...
post.setEntity(new UrlEncodedFormEntity(params));
HttpResponse mHTTPResponse = client.execute(post);
StatusLine statusLine = mHTTPResponse.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { //
//get response
BufferedReader rd = new BufferedReader(new InputStreamReader(
mHTTPResponse.getEntity().getContent()));
StringBuilder builder = new StringBuilder();
String aux = "";
while ((aux = rd.readLine()) != null) {
builder.append(aux);
}
mResponse = builder.toString();
} else {
//cancel task and show error
Log.e(DEBUG_TAG, "ERROR in Request:" + statusCode);
this.cancel(true);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return mResponse;
}

Post JSON in android

I want to post String data over HttpClient in android
but i'm tired after receive response status code 503 - service unavailable and
return response as Html code for our url.
I write in the following Code in JAVA Application and i return the data but when I write the same code in Android Application i receive an exception file I/O not found, I'm Puzzled for this case:
public void goButton(View v)
{
try{
URL url = new URL("https://xxxxxxxxx");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
Test ts= new ApiRequest("null","getUserbyID",new String[] { "66868706" });
String payLoad = ts.toString(); //toSting is override method that create //JSON Object
System.out.println("--->>> " + payLoad);
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
System.out.println("=================>>> "+ payLoad);
wr.write(payLoad);
wr.flush();
BufferedReader rd = new BufferedReader(new nputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
System.out.println("-->> " + line);
response += line;
}
wr.close();
rd.close();
System.out.println("=================>>> "+ response);
} catch (Exception e) {
e.printStackTrace();
System.out.println("=================>>> " + e.toString());
throw new RuntimeException(e);
}
I try to put this code in AsynTask, Thread but i receive the same response status code.
I write in the following Android code as an example data
public void goButton(View v)
{
try{
new Thread(new Runnable() {
public void run() {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(),
10000); // Timeout Limit
HttpResponse response;
String url = "https://xxxxxxxxxxxxx";
JSONObject json = new JSONObject();
try {
HttpPost post = new HttpPost(url);
post.setHeader("Content-type", "application/json");
json.put("service","null");
json.put("method", getUserByID.toString());
json.put("parameters", "1111");
System.out.println(">>>>>>>>>>>" + json.toString());
StringEntity se = new StringEntity(json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
post.setEntity(se);
String response = client.execute(post);
if (response != null) {
String temp = EntityUtils.toString(response.getEntity());
System.out.println(">>>>>>>>>>>" + temp);
}
} catch (Exception e) {
e.printStackTrace();
System.out.println(">>>>>>>>>>>" + e.getMessage());
}
}
}).start();
}
Please Help me to find solution for this problem :(
Thank you in advance
Here is an code snippet , hoping it will help you.
1)An function which carries the http get service
private String SendDataFromAndroidDevice() {
String result = "";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet getMethod = new HttpGet("your url + data appended");
BufferedReader in = null;
BasicHttpResponse httpResponse = (BasicHttpResponse) httpclient
.execute(getMethod);
in = new BufferedReader(new InputStreamReader(httpResponse
.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
while ((line = in.readLine()) != null) {
sb.append(line);
}
in.close();
result = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
2) An Class which extends AsyncTask
private class HTTPdemo extends
AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {}
#Override
protected String doInBackground(String... params) {
String result = SendDataFromAndroidDevice();
return result;
}
#Override
protected void onProgressUpdate(Void... values) {}
#Override
protected void onPostExecute(String result) {
if (result != null && !result.equals("")) {
try {
JSONObject resObject = new JSONObject(result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
3) Inside your onCreate method
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView("your layout");
if ("check here where network/internet is avaliable") {
new HTTPdemo().execute("");
}
}
This code snippet ,
Android device will send the data via URL towards Server
now server needs to fetch that data from the URL
Hey Mohammed Saleem
The code snippet provided by me works in the following way,
1)Android device send the URL+data to server
2)Server [say ASP.NET platform used] receive the data and gives an acknowledgement
Now the Code which should be written at client side (Android) is provided to you, the later part of receiving that data at server is
Server needs to receive the data
An webservice should be used to do that
Implement an webservice at server side
The webservice will be invoked whenever android will push the URL+data
Once you have the data ,manipulated it as you want

Retrieve the http code of the response in java

I have the following code for make a post to an url an retrieve the response as a String. But I'd like to get also the HTTP response code (404,503, etc). Where can I recover it?
I've tried with the methods offered by the HttpReponse class but didn't find it.
Thanks
public static String post(String url, List<BasicNameValuePair> postvalues) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
if ((postvalues == null)) {
postvalues = new ArrayList<BasicNameValuePair>();
}
httppost.setEntity(new UrlEncodedFormEntity(postvalues, "UTF-8"));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
return requestToString(response);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private static String requestToString(HttpResponse response) {
String result = "";
try {
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
str.append(line + "\n");
}
in.close();
result = str.toString();
} catch (Exception ex) {
result = "Error";
}
return result;
}
You can modify your code like this:
//...
HttpResponse response = httpclient.execute(httppost);
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
//edit: there is already function for this
return EntityUtils.toString(response.getEntity(), "UTF-8");
} else {
//Houston we have a problem
//we should do something with bad http status
return null;
}
EDIT: just one more thing ...
instead of requestToString(..); you can use EntityUtils.toString(..);
Have you tried this?
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
response.getStatusLine().getStatusCode();
Have you tried the following?
response.getStatusLine().getStatusCode()

Post url from android to retrieve data

i have a url "http://184.82.158.234/~store/rest/system/connect.json" and posting this url with mozilla addon called poster returns data in form of json
what i want is to post this url from android to get that json data into androids view .
any help is highly appreciated
thanks
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://184.82.158.234/~store/rest/system/connect.json");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
response variable will contain your json data.
Here is a function maybe you can use to post a string to a URL.
public String doHttpPost(final String fullUrl, final String body) {
final URL url = new URL(fullUrl);
final HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
// set the request mode as POST
urlConnection.setRequestMethod("POST");
urlConnection.setUseCaches(false);
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Accept-charset", "utf-8");
urlConnection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
final DataOutputStream request = new DataOutputStream(urlConnection.getOutputStream());
// write the body.
request.writeBytes(body);
// flush output buffer
request.flush();
request.close();
// construct a read using input stream and charset.
final InputStreamReader isr = new InputStreamReader(urlConnection.getInputStream(), CHARSET_UTF8);
final BufferedReader in = new BufferedReader(isr);
String inputLine;
final StringBuilder stringBuilder = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
stringBuilder.append(inputLine).append("\n");
}
in.close();
isr.close();
urlConnection.disconnect();
return stringBuilder.toString();
}
check below code: try this it may help you.
ArrayList nameValuePairs1 = new ArrayList();
nameValuePairs1.add(new BasicNameValuePair("user_id", ""));
nameValuePairs1.add(new BasicNameValuePair("product_id", ""));
nameValuePairs1.add(new BasicNameValuePair("product_review",""+text));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs1));
HttpResponse responce = httpclient.execute(httppost);
HttpEntity entity = responce.getEntity();
is = entity.getContent();
BufferedReader bufr = new BufferedReader(new InputStreamReader(is1,"iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
sb.append(bufr.readLine() + "\n");
String line = "0";
while ((line = bufr.readLine()) != null)
{
sb.append(line + "\n");
}
is1.close();
result = sb.toString();
result is a json String. parse that json and display in any control. i displaied that in text view see below.
final MyProgressDialog progDailog = new MyProgressDialog(Cheking_Review.this);
final Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
if (Name.length() > 0 && Name != null) {
txtvenue.setText(Name);
} else {
txtvenue.setText(venue_name);
}
}
};
new Thread() {
public void run() {
try {
// put your result here
JSONObject jObject = new JSONObject(result);
JSONObject menuObject = jObject.getJSONObject("response");
JSONObject venueObject = menuObject.getJSONObject("venue");
Name = venueObject.getString("name");
String id = venueObject.getString("id");
Log.d("--------name---------", Name);
Log.d("--------id---------", id);
} catch (Exception e) {
}
handler.sendEmptyMessage(0);
progDailog.dismiss();
}
}.start();

Categories

Resources