I am trying to make a login and register for an android app.
I have been having problems adjusting the code to API 22.
Although I know I have to use HttpURLConnection instead of HttpRequestParams etc., and have done that, I can't figure out how to adjust the code to incorporate the database server and my PHP files stored on there.
It's mostly this bit below that I can't figure out.
HttpClient client = new DefaultHttpClient(httpRequestParams);
HttpPost post = new HttpPost(SERVER_ADDRESS + "FetchUserData.php");
Can anyone help? Thanks in advance.
Here's the full code:
#Override
protected User doInBackground(Void... params) {
ContentValues contentValues = new ContentValues();
contentValues.put("username", user.username);
contentValues.put("password", user.password);
URL url = new URL(SERVER_ADDRESS);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setReadTimeout(CONNECTION_TIMEOUT);
HttpClient client = new DefaultHttpClient(httpRequestParams);
HttpPost post = new HttpPost(SERVER_ADDRESS + "FetchUserData.php");
User returnedUser = 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) {
returnedUser = null;
} else {
String mobile = jObject.getString("mobile");
String email = jObject.getString("email");
returnedUser = new User(mobile, email, user.mobile, user.email);
}
} catch(Exception e) {
e.printStackTrace();
}
return returnedUser;
}
first: It's already been answered
Sending Http request for Android 22+
second: I've made a class that meets your needs, which allow you to send request and receive response with one line of code (It's also explained in post above)
Here is the link for the my class:
HttpRequest
Related
When I used HttpUrlConnection to send POST request from Android to ASP.net Web API. It seems not working.
String baseUrl = "http://<IP Address>/Save/Document";
URL url = new URL(baseUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
DataOutputStream os = new DataOutputStream(conn.getOutputStream());
JSONObject ap = new JSONObject();
// Where data is a JSON string
// Like [{Test: 1}, {Test: 2}]
ap.put("",new Gson().toJson(data));
OutputStreamWriter ap_osw= new OutputStreamWriter(conn.getOutputStream());
ap_osw.write(ap.toString());
ap_osw.flush();
ap_osw.close();
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
StringBuilder response = new StringBuilder();
while ((output = br.readLine()) != null) {
response.append(output);
response.append('\r');
}
String mes = response.toString();
Log.i("INFO", mes);
conn.disconnect();
When executing the above code, it will have an FileNotFoundException in
conn.getInputStream()
I also tried to implement source code in HttpClient style.
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(baseUrl);
try {
StringEntity se = new StringEntity((new Gson()).toJson(data));
httpPost.setEntity(se);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-Type", "application/json");
HttpResponse response = httpClient.execute(httpPost);
InputStream inputStream = response.getEntity().getContent();
String result = "";
if (inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
Log.i("RESPONSE", result);
} catch (Exception ex) {
Log.i("Exception", ex.getMessage());
}
return output;
And this time, it shows "The requested resource does not support http method 'get'".
I have no ideas how to implement the POST request method to send data from Android to ASP.net Web API. Any recommendations?
Finally, the following coding is my ASP.net Web API for reference.
[HttpPost]
[Route("Save/Document")]
public HttpResponseMessage Post([FromBody]string model)
{
var resp = new HttpResponseMessage(HttpStatusCode.OK);
resp.Content = new StringContent(model, System.Text.Encoding.UTF8, "text/plain");
return resp;
}
Finally, I got a solution to fix this problem. It is due to the POST data in request body can not be read from Web API.
When the request Content-Type is "application/json",
Using string, The request body should be a plain text (e.g. "Text Message").
[FromBody] string inStr
Using self-defined class, The request body should be a json string
(e.g { KEY: VALUE })
[FromBody] YourClass inObj
Using array of self-defined class, The request body should be a json array string (e.g [{ KEY: VALUE }])
[FromBody] YourClass[] inObj
And the self-defined class should be like as following:-
class YourClass {
public string KEY { get; set; }
}
Btw. Thanks for all reply and useful information.
When I use Follow/Unfollow API in instagram. I give me error like that.
Error:
{"meta":{"error_type":"OAuthPermissionsException","code":400,"error_message":"This client has not been approved to access this resource."}}
My Post method Call is here.
public static AllMessage postAction(String action, String UserID, String mAccessToken, DefaultHttpClient httpClient) {
AllMessage ReturnMessage = new AllMessage();
String url = String.format(RELATIONSHIP_URL, new Object[]{UserID, mAccessToken});
Log.v("log_tag", "FolURL " + url);
try {
HttpParams params = new BasicHttpParams();
params.setParameter("http.protocol.version", HttpVersion.HTTP_1_1);
params.setParameter("action=", action);
if (httpClient == null) {
httpClient = OpenHttpClientConnection();
}
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> arrayList = new ArrayList(2);
arrayList.add(new BasicNameValuePair("action", action));
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", String.valueOf(arrayList));
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(arrayList, "UTF-8");
httpPost.setEntity(ent);
String mHttpReturnedData = readInputStreamToString(httpClient.execute(httpPost).getEntity().getContent());
Log.v("log_tag", "Return " + mHttpReturnedData);
} catch (Exception e4) {
ReturnMessage.MessageType = "Unsupported Format";
ReturnMessage.MessageError = "Unsupported data format Error -1000";
ReturnMessage.ActionSucess = false;
ReturnMessage.ActionID = 0;
ReturnMessage.PrvAction = action;
}
return ReturnMessage;
}
Please help me for this code.
You need to first register your app to use the Instagram API
The link is here https://www.instagram.com/developer/endpoints/
Then you comunicate with the endpoint https://api.instagram.com/v1/tags/nofilter/media/recent?access_token=ACCESS_TOKEN
and make the proper calls.
Currently there is not an Android SDK made by them that I have heard of, but I'm pretty sure there has to be a 3rd party out there.
Hope it helps.
in my app i need to post data to an url to register a new user. Here is the url
http://myurl.com/user.php? email=[EMAIL]&username=[USERNAME]&password[PASS]&img_url=[IMG]
If I do that correctly I should get this message:
{"success":true,"error":null}
or if not {"success":false,"error":"parameters"}
Can somebody guide me through this and tell me how can I do it.
first :
you need to perform all network tasks in an Async thread using:
public class PostData extends AsyncTask<String, Void, String>{
{
#Override
protected String doInBackground(String... params) {
//put all your network code here
}
Second:
create your http request:
i am assuming email, username and IMG as variables over here.
String server ="http://myurl.com/user.php? email=[" + EMAIL + "]&username=[" + USERNAME + "]&password[" + PASS + "]&img_url=["+IMG + "]";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(server);
//httppost.setHeader("Accept", "application/json");
httppost.setHeader("Accept", "application/x-www-form-urlencoded");
//httppost.setHeader("Content-type", "application/json");
httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");
third:
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("JSONdata", Object));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));
try {
HttpResponse response =httpclient.execute(httppost);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Now simple query your response handler i.e. response in this case.
Don't forget to add INTERNET permission in your androidManifest.xml
Hope this helps!
Use a HTTP client class, and format your URL via a specific URI constructor. Create a HTTP post, optionally set the entity, headers, etc, execute the post via the client, receive a HTTP response, pull the entity out of the response and process it.
EDIT for example:
HttpClient httpclient = new DefaultHttpClient();
URI uri = new URI("http",
"www.google.com", // connecting to IP
"subpath", // and the "path" of what we want
"a=5&b=6", // query
null); // no fragment
HttpPost httppost = new HttpPost(uri.toASCIIString);
// have a body ?
// post.setEntity(new StringEntity(JSONObj.toString()));
// post.setHeader("Content-type", "application/json");
HttpResponse response = httpClient.execute(post);
int statusCode = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
Reader r = new InputStreamReader(entity.getContent());
// Do something with the data in the reader.
I've been trying this for the best part of two weeks now, and I am really stuck. Initially I had created a simple ObjectOutputStream client - server program - with the client being the Android app, but it does not work (it reads the connection but not the object).
So now I am confused as to what other approaches I might be able to take to carry out this simple task? Can anyone Help?
have you tried URLConnection using post method? :)
Or get method like:
String yourURL = "www.yourwebserver.com?value1=one&value2=two";
URL url = new URL(yourURL);
URLConnection connection = url.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
response = in.readLine();
you can try JSON stirng to send data. We have a lot of stuff available on how to work with JSON and also there are many api's. JSONSimple is the one I can suggest. Its really easy.
why don't you try this:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
You can use this to post an Entity to server:
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(url);
postRequest.setEntity(entity);
try {
HttpResponse response = httpClient.execute(postRequest
);
String jsonString = EntityUtils.toString(response
.getEntity());
Log.v(ProgramConstants.TAG, "after uploading file "
+ jsonString);
return jsonString;
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
An Entity can be name value pair:
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("key1", value1));
nvps.add(new BasicNameValuePair("key2", value2));
Entity entity=new UrlEncodedFormEntity(nvps, HTTP.UTF_8)
Or you can send an entity with bytearray.
Bitmap bitmapOrg=getBitmapResource();
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte[] data = bao.toByteArray();
MultipartEntity entity=new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE)
entity.addPart("file", new ByteArrayBody(data, "image/jpeg",
"file"));
If you want to post json to server:
Please check out this link How do I send JSon as BODY In a POST request to server from an Android application?
For serializing and deserializing java object, I recommend https://sites.google.com/site/gson/gson-user-guide#TOC-Using-Gson
Really hope it can help you see an overview of sending data to server
I'm trying to figure out how to POST JSON from Android by using HTTPClient. I've been trying to figure this out for a while, I have found plenty of examples online, but I cannot get any of them to work. I believe this is because of my lack of JSON/networking knowledge in general. I know there are plenty of examples out there but could someone point me to an actual tutorial? I'm looking for a step by step process with code and explanation of why you do each step, or of what that step does. It doesn't need to be a complicated, simple will suffice.
Again, I know there are a ton of examples out there, I'm just really looking for an example with an explanation of what exactly is happening and why it is doing that way.
If someone knows about a good Android book on this, then please let me know.
Thanks again for the help #terrance, here is the code I described below
public void shNameVerParams() throws Exception{
String path = //removed
HashMap params = new HashMap();
params.put(new String("Name"), "Value");
params.put(new String("Name"), "Value");
try {
HttpClient.SendHttpPost(path, params);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
In this answer I am using an example posted by Justin Grammens.
About JSON
JSON stands for JavaScript Object Notation. In JavaScript properties can be referenced both like this object1.name and like this object['name'];. The example from the article uses this bit of JSON.
The Parts
A fan object with email as a key and foo#bar.com as a value
{
fan:
{
email : 'foo#bar.com'
}
}
So the object equivalent would be fan.email; or fan['email'];. Both would have the same value
of 'foo#bar.com'.
About HttpClient Request
The following is what our author used to make a HttpClient Request. I do not claim to be an expert at all this so if anyone has a better way to word some of the terminology feel free.
public static HttpResponse makeRequest(String path, Map params) throws Exception
{
//instantiates httpclient to make request
DefaultHttpClient httpclient = new DefaultHttpClient();
//url with the post data
HttpPost httpost = new HttpPost(path);
//convert parameters into JSON object
JSONObject holder = getJsonObjectFromMap(params);
//passes the results to a string builder/entity
StringEntity se = new StringEntity(holder.toString());
//sets the post request as the resulting string
httpost.setEntity(se);
//sets a request header so the page receving the request
//will know what to do with it
httpost.setHeader("Accept", "application/json");
httpost.setHeader("Content-type", "application/json");
//Handles what is returned from the page
ResponseHandler responseHandler = new BasicResponseHandler();
return httpclient.execute(httpost, responseHandler);
}
Map
If you are not familiar with the Map data structure please take a look at the Java Map reference. In short, a map is similar to a dictionary or a hash.
private static JSONObject getJsonObjectFromMap(Map params) throws JSONException {
//all the passed parameters from the post request
//iterator used to loop through all the parameters
//passed in the post request
Iterator iter = params.entrySet().iterator();
//Stores JSON
JSONObject holder = new JSONObject();
//using the earlier example your first entry would get email
//and the inner while would get the value which would be 'foo#bar.com'
//{ fan: { email : 'foo#bar.com' } }
//While there is another entry
while (iter.hasNext())
{
//gets an entry in the params
Map.Entry pairs = (Map.Entry)iter.next();
//creates a key for Map
String key = (String)pairs.getKey();
//Create a new map
Map m = (Map)pairs.getValue();
//object for storing Json
JSONObject data = new JSONObject();
//gets the value
Iterator iter2 = m.entrySet().iterator();
while (iter2.hasNext())
{
Map.Entry pairs2 = (Map.Entry)iter2.next();
data.put((String)pairs2.getKey(), (String)pairs2.getValue());
}
//puts email and 'foo#bar.com' together in map
holder.put(key, data);
}
return holder;
}
Please feel free to comment on any questions that arise about this post or if I have not made something clear or if I have not touched on something that your still confused about... etc whatever pops in your head really.
(I will take down if Justin Grammens does not approve. But if not then thanks Justin for being cool about it.)
Update
I just happend to get a comment about how to use the code and realized that there was a mistake in the return type.
The method signature was set to return a string but in this case it wasnt returning anything. I changed the signature
to HttpResponse and will refer you to this link on Getting Response Body of HttpResponse
the path variable is the url and I updated to fix a mistake in the code.
Here is an alternative solution to #Terrance's answer. You can easly outsource the conversion. The Gson library does wonderful work converting various data structures into JSON and the other way around.
public static void execute() {
Map<String, String> comment = new HashMap<String, String>();
comment.put("subject", "Using the GSON library");
comment.put("message", "Using libraries is convenient.");
String json = new GsonBuilder().create().toJson(comment, Map.class);
makeRequest("http://192.168.0.1:3000/post/77/comments", json);
}
public static HttpResponse makeRequest(String uri, String json) {
try {
HttpPost httpPost = new HttpPost(uri);
httpPost.setEntity(new StringEntity(json));
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
return new DefaultHttpClient().execute(httpPost);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
Similar can be done by using Jackson instead of Gson. I also recommend taking a look at Retrofit which hides a lot of this boilerplate code for you. For more experienced developers I recommend trying out RxAndroid.
I recommend using this HttpURLConnectioninstead HttpGet. As HttpGet is already deprecated in Android API level 22.
HttpURLConnection httpcon;
String url = null;
String data = null;
String result = null;
try {
//Connect
httpcon = (HttpURLConnection) ((new URL (url).openConnection()));
httpcon.setDoOutput(true);
httpcon.setRequestProperty("Content-Type", "application/json");
httpcon.setRequestProperty("Accept", "application/json");
httpcon.setRequestMethod("POST");
httpcon.connect();
//Write
OutputStream os = httpcon.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(data);
writer.close();
os.close();
//Read
BufferedReader br = new BufferedReader(new InputStreamReader(httpcon.getInputStream(),"UTF-8"));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
result = sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Too much code for this task, checkout this library https://github.com/kodart/Httpzoid
Is uses GSON internally and provides API that works with objects. All JSON details are hidden.
Http http = HttpFactory.create(context);
http.get("http://example.com/users")
.handler(new ResponseHandler<User[]>() {
#Override
public void success(User[] users, HttpResponse response) {
}
}).execute();
There are couple of ways to establish HHTP connection and fetch data from a RESTFULL web service. The most recent one is GSON. But before you proceed to GSON you must have some idea of the most traditional way of creating an HTTP Client and perform data communication with a remote server. I have mentioned both the methods to send POST & GET requests using HTTPClient.
/**
* This method is used to process GET requests to the server.
*
* #param url
* #return String
* #throws IOException
*/
public static String connect(String url) throws IOException {
HttpGet httpget = new HttpGet(url);
HttpResponse response;
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 60*1000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 60*1000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpClient httpclient = new DefaultHttpClient(httpParameters);
try {
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
result = convertStreamToString(instream);
//instream.close();
}
}
catch (ClientProtocolException e) {
Utilities.showDLog("connect","ClientProtocolException:-"+e);
} catch (IOException e) {
Utilities.showDLog("connect","IOException:-"+e);
}
return result;
}
/**
* This method is used to send POST requests to the server.
*
* #param URL
* #param paramenter
* #return result of server response
*/
static public String postHTPPRequest(String URL, String paramenter) {
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 60*1000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 60*1000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpClient httpclient = new DefaultHttpClient(httpParameters);
HttpPost httppost = new HttpPost(URL);
httppost.setHeader("Content-Type", "application/json");
try {
if (paramenter != null) {
StringEntity tmp = null;
tmp = new StringEntity(paramenter, "UTF-8");
httppost.setEntity(tmp);
}
HttpResponse httpResponse = null;
httpResponse = httpclient.execute(httppost);
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
InputStream input = null;
input = entity.getContent();
String res = convertStreamToString(input);
return res;
}
}
catch (Exception e) {
System.out.print(e.toString());
}
return null;
}