Code doesn't work when server response the request - android

Recently I'm learning the request and response between server and android .
I try to update a JSON file when server responses but I'm failed. the update code doesn't work.
the server code like this:after the code"JSONArray"doesn't work but i don't know why.
public class AndroidServerServlet extends HttpServlet {
private static final long serialVersionUID = 6792396567928634227L;
public void doPost(HttpServletRequest request,
HttpServletResponse response)throws ServletException, IOException {
response.setContentType("text/plain; charset=UTF-8");
request.setCharacterEncoding("UTF-8");
String username = request.getParameter("username");
String newPassword = request.getParameter("newpassword");
PrintWriter printWriter = response.getWriter();
printWriter.print("hello android, password changed");
printWriter.flush();
printWriter.close();
System.out.println(username+"\n"+newPassword);
ChangePassword(username , newPassword);
}
private void ChangePassword(String username , String password){
try {
InputStream in = AndroidServerServlet.class
.getClassLoader().getResourceAsStream("/1.json");
Scanner scanner = new Scanner(in, "UTF-8"); //InputStream → String
String jsonData = scanner.useDelimiter("\\A").next();
System.out.println(jsonData);
scanner.close();
JSONArray jsonArray = new JSONArray(jsonData);
for(int i = 0;i < jsonArray.length(); i++){
JSONObject object = jsonArray.getJSONObject(i);
if(username.equals(object.getString("username")))
object.put("password",password);
}
System.out.println(jsonData);
in.close();
}catch (Exception e){
System.out.print("Exception\n");
}
}
}
the android code like this:(surbmit is a button)
surbmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RequestParams requestParams = new RequestParams();
requestParams.add("newpassword", "newpassword");
requestParams.add("username","test1");
new AsyncHttpClient().post("http://10.0.2.2:8080/AndroidServerServlet", requestParams, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
if(statusCode == 200){
Toast.makeText(MainActivity.this, new String(responseBody), Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Toast.makeText(MainActivity.this, "server doesn't response", Toast.LENGTH_LONG).show();
}
});
}
});
and the json file is this:
[{"username":"test1","password":"password1"},
{"username":"test2","password":"password2"},
{"username":"test3","password":"password3"}]
When I debug the server code,I found a ERROR:java.long.NoClassDefFoundError:org/json/JSONArray.but I have alerady add that jar in the project,why the error comming?
BTW:I use IntelliJ IDEA + MAVEN + Tomcat to build my server.
the error report:
java.lang.NoClassDefFoundError: org/json/JSONArray
at AndroidServerServlet.ChangePassword(AndroidServerServlet.java:41)
at AndroidServerServlet.doPost(AndroidServerServlet.java:31)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:783)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:789)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1437)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
I tried to delete the jar I had added and the wrong report is still same as top,proved that I didn't add the jar really,but how can I add it?

May I suggest using HttpUrlConnection instead of ServletRequest/Response, Scanner, etc ...
Please check this link:https://developer.android.com/reference/java/net/HttpURLConnection.html
You'll find a sample in the Posting Content section.

Related

How to send json data from Android to Asp.net

Help me to post json data from Android to Asp.net
Here is my code below. Android sending json data to webapi
public class UploadByTableActivity extends Activity {
final static String url = "https://webapi.com/api/post/";
HttpResponse response;
AsyncHttpClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_uploadbytable);
Button btnWO = (Button) findViewById(R.id.btnwo);
btnWorkOrder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
JSONObject jsonParams = new JSONObject();
String username = "id";
String password = "pw";
client = new AsyncHttpClient(true, 80, 443);
client.addHeader(
"Authorization",
"Basic " + Base64.encodeToString(
(username + ":"+ password).getBytes(),Base64.NO_WRAP)
);
client.setEnableRedirects(true);
RequestParams params = new RequestParams();
// params.put("file", new File(pathoffile));
params.put("name", "name1");
params.put("phone", "111-111-1111");
StringEntity entity = null;
try {
entity = new StringEntity(params.toString());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
client.post(null,url,entity, "application/json", new AsyncHttpResponseHandler(Looper.getMainLooper()) {
#Override
public void onSuccess(int i, Header[] headers, byte[] bytes) {
Log.i("appTag", "OK");
}
#Override
public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
Log.i("appTag"," Error = " + throwable.getMessage());
}
});
}
});
}
Try to retrieve jsondata from webapi to asp.net but jsonString is null.
Please help me how to get json data.
[HttpPost]
public string post([FromBody]string jsonString){
return jsonString;
}

Getting statusCode of 400 from GET

I am trying to do a get from the API, but it returns a 400, I have tried putting my local IP and putting 10.0.2.2, but he has continued to do the same, in the Event Log shows me this too: Emulator: CANNOT TRANSLATE guest DNS ip.From the PostMan I get the JSON back correctly so I do not think the problem is in the API
This is where I do everything
public void PendingTrajects(){
AsyncHttpClient client = new AsyncHttpClient();
String URL = "http://ip:port/api/trajectes";
client.get(this, URL, new AsyncHttpResponseHandler() {
#Override
public void onStart() {
Toast.makeText(PendingTrajectRecyclerView.this, "Carregant...", Toast.LENGTH_SHORT).show();
}
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
JSONArray Usuaris = new JSONArray();
JSONArray trajectes = new JSONArray();
String Nom = null;
String strResponseBody = new String(responseBody);
try {
//Usuari = new JSONArray(strResponseBody);
trajectes = new JSONArray(strResponseBody);
}catch (JSONException e){
Toast.makeText(PendingTrajectRecyclerView.this, "Error a la connexió", Toast.LENGTH_SHORT).show();
}
try {
for(int i = 0; i < trajectes.length(); i++){
JSONObject trajecte = trajectes.getJSONObject(i);
JSONArray realitzas = trajecte.getJSONArray("realitzas");
for(int j = 0; j < realitzas.length(); j++){
JSONObject realitza = realitzas.getJSONObject(j);
JSONObject usuari = realitza.getJSONObject("usuari");
Log.d("xd", ""+usuari.getString("name"));
}
}
}catch (JSONException e){
Toast.makeText(PendingTrajectRecyclerView.this, "Error a la connexió", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(int statusCode, cz.msebera.android.httpclient.Header[] headers, byte[] responseBody, Throwable error) {
Toast.makeText(PendingTrajectRecyclerView.this, "Error a la connexió ONFailure", Toast.LENGTH_SHORT).show();
Log.d("Error",""+statusCode);
}
});
400 BAD REQUEST
The server cannot or will not process the request due to something
that is perceived to be a client error (e.g., malformed request
syntax, invalid request message framing, or deceptive request
routing).
You should DEBUG your Application. Check your parameters.
Add a Break-point here
String URL = "http://ip:port/api/trajectes";
Actually server could not understand the request due to invalid syntax.

Loopj - Uploading Files with RequestParams c# .net

Trying to upload a file with params using loopj.
im trying to get file from Request.Files and params from Request.Form["create"]
but it is not uploading to the server.
Android Post method
try {
String createTeamURL = "http://url";
RequestParams params = new RequestParams();
params.put("file", new File(pathoffile));
params.add("create", regString);
AsyncHttpClient client = new AsyncHttpClient();
client.post(createTeamURL, params, new AsyncHttpResponseHandler() {
#Override
public void onStart() {
// called before request is started
}
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
// called when response HTTP status is "200 OK"
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
// called when response HTTP status is "4XX" (eg. 401, 403, 404)
}
#Override
public void onRetry(int retryNo) {
// called when request is retried
}
});
} catch (Exception e) {
Log.e("createTeamPreStep", e.getMessage());
}
My Web Api c# method
[HttpPost]
public async Task<string> CreateUHS()
{
var resultString = "";
foreach(HttpPostedFileBase s in Request.Files)
{
var a=s;
}
String sdf = Request.Form["create"];
}
You need to use put for string args.
please find the below both server and client methods.
and one more thing im really worried about your naming variable. its bad. please change it. Happy coding.
String createTeamURL = "http://url";
RequestParams params = new RequestParams();
params.put("file", new File(pathoffile));
params.put("create", regString);
Server (Web api)
[HttpPost]
public async Task<string> CreateUHS()
{
var file=Request.Files[0];
String otherArg = Request.Form["create"];
}

Get JSON data from LoopJ AndroidAsyncHttp

I am trying to get response from my node.js server with MySQL database.
When I connect to server with my browser I get result like this:
[{"person_id":0,"age":18},{"person_id":1,"age":17},{"person_id":2,"age":30}]
What I want to do is to get the same result with my Android app after pressing the button.
I wanted to use LoopJ AndroidAsyncHttp:
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://localhost:3000", new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
super.onSuccess(statusCode, headers, response);
}
});
I know that I connected to server properly because I got log in server's console.
What is the easiest way to retrieve that data?
Create a model Person contain "person_id" and "age"
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://localhost:3000",new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
try {
String response = responseBody == null ? null : new String(
responseBody, getCharset());
Log.d("Response: ", response);
Gson gson = new Gson();
Person[] arr = gson.fromJson(response, Person[].class);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}

POSTing JSON/XML using android-async-http (loopj)

I am using android-async-http and really liking it. I've run into a problem with POSTing data. I have to post data to the API in the following format: -
<request>
<notes>Test api support</notes>
<hours>3</hours>
<project_id type="integer">3</project_id>
<task_id type="integer">14</task_id>
<spent_at type="date">Tue, 17 Oct 2006</spent_at>
</request>
As per the documentation, I tried doing it using RequestParams, but it is failing. Is this any other way to do it? I can POST equivalent JSON too. Any ideas?
Loopj POST examples - extended from their Twitter example:
private static AsyncHttpClient client = new AsyncHttpClient();
To post normally via RequestParams:
RequestParams params = new RequestParams();
params.put("notes", "Test api support");
client.post(restApiUrl, params, responseHandler);
To post JSON:
JSONObject jsonParams = new JSONObject();
jsonParams.put("notes", "Test api support");
StringEntity entity = new StringEntity(jsonParams.toString());
client.post(context, restApiUrl, entity, "application/json",
responseHandler);
#Timothy answer did not work for me.
I defined the Content-Type of the StringEntity to make it work:
JSONObject jsonParams = new JSONObject();
jsonParams.put("notes", "Test api support");
StringEntity entity = new StringEntity(jsonParams.toString());
entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
client.post(context, restApiUrl, entity, "application/json", responseHandler);
Good Luck :)
a better way to post json
RequestParams params = new RequestParams();
params.put("id", propertyID);
params.put("lt", newPoint.latitude);
params.put("lg", newPoint.longitude);
params.setUseJsonStreamer(true);
ScaanRestClient restClient = new ScaanRestClient(getApplicationContext());
restClient.post("/api-builtin/properties/v1.0/edit/location/", params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
}
});
To post XML
protected void makePost() {
AsyncHttpClient client = new AsyncHttpClient();
Context context = this.getApplicationContext();
String url = URL_String;
String xml = XML-String;
HttpEntity entity;
try {
entity = new StringEntity(xml, "UTF-8");
} catch (IllegalArgumentException e) {
Log.d("HTTP", "StringEntity: IllegalArgumentException");
return;
} catch (UnsupportedEncodingException e) {
Log.d("HTTP", "StringEntity: UnsupportedEncodingException");
return;
}
String contentType = "string/xml;UTF-8";
Log.d("HTTP", "Post...");
client.post( context, url, entity, contentType, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
Log.d("HTTP", "onSuccess: " + response);
}
... other handlers
});
}
just write your xml or json to a string and send to server, with proper headers or without. and yes set "Content-Type" to "application/json"
If someone have a problem that httpclient send as Content-Type: text/plain, please refer this link: https://stackoverflow.com/a/26425401/361100
The loopj httpclient is somewhat changed (or has problem) which cannot override StringEntity native Content-Type to application/json.
You can add the JSON string as an InputStream of some kind - I've used the ByteArrayStream, then passing it to the RequestParams you should set the correctMimeType
InputStream stream = new ByteArrayInputStream(jsonParams.toString().getBytes(Charset.forName("UTF-8")));
multiPartEntity.put("model", stream, "parameters", Constants.MIME_TYPE_JSON);
Just make JSONObject and then convert it to String "someData" and simply send with "ByteArrayEntity"
private static AsyncHttpClient client = new AsyncHttpClient();
String someData;
ByteArrayEntity be = new ByteArrayEntity(someData.toString().getBytes());
client.post(context, url, be, "application/json", responseHandler);
It is working fine for me.
To post xml file to a php server :
public class MainActivity extends AppCompatActivity {
/**
* Send xml file to server via asynchttpclient lib
*/
Button button;
String url = "http://xxx/index.php";
String filePath = Environment.getExternalStorageDirectory()+"/Download/testUpload.xml";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
postFile();
}
});
}
public void postFile(){
Log.i("xml","Sending... ");
RequestParams params = new RequestParams();
try {
params.put("key",new File(filePath));
}catch (FileNotFoundException e){
e.printStackTrace();
}
AsyncHttpClient client = new AsyncHttpClient();
client.post(url, params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int i, cz.msebera.android.httpclient.Header[] headers, byte[] bytes) {
Log.i("xml","StatusCode : "+i);
}
#Override
public void onFailure(int i, cz.msebera.android.httpclient.Header[] headers, byte[] bytes, Throwable throwable) {
Log.i("xml","Sending failed");
}
#Override
public void onProgress(long bytesWritten, long totalSize) {
Log.i("xml","Progress : "+bytesWritten);
}
});
}
}
After adding android-async-http-1.4.9.jar to android studio,
go to build.gradle and add :
compile 'com.loopj.android:android-async-http:1.4.9' under dependencies
And on AndroidManifest.xml add:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Categories

Resources