Split nested json data - java
I am trying to split nested json data
private String TickData(String token) {
OkHttpClient client = new OkHttpClient().newBuilder().build();
Request request = new Request.Builder()
.url("https://history.truedata.in/getticks?symbol=NIFTY 50&from=211201T09:15:00&to=211201T15:30:00&response=json&bidask=1")
.method("GET", null)
.addHeader("Authorization", "Bearer " + token)
.build();
try {
Response response = client.newCall(request).execute();
Log.d(TAG, "TickData: tick data response: " + response.body().string());
String s = response.body().string();
Log.e(TAG, "TickData: s: " + s );
} catch (Exception e) {
e.printStackTrace();
}
return tickdata;
}
this is my nested json data.
{"status":"Success","Records":[["2021-12-01T09:15:00",17104.4,0,0,0.0,0,0.0,0],["2021-12-01T09:15:00",17105.05,0,0,0.0,0,0.0,0],["2021-12-01T09:15:00",17082.0,0,0,0.0,0,0.0,0],["2021-12-01T09:15:00",17082.0,0,0,0.0,0,0.0,0],["2021-12-01T09:15:01",17079.75,0,0,0.0,0,0.0,0],["2021-12-01T09:15:01",17085.1,0,0,0.0,0,0.0,0],["2021-12-01T09:15:02",17088.65,0,0,0.0,0,0.0,0],["2021-12-01T09:15:03",17090.7,0,0,0.0,0,0.0,0],["2021-12-01T09:15:04",17095.3,0,0,0.0,0,0.0,0],["2021-12-01T09:15:05",17099.4,0,0,0.0,0,0.0,0],["2021-12-01T09:15:06",17106.05,0,0,0.0,0,0.0,0],["2021-12-01T09:15:06",17105.75,0,0,0.0,0,0.0,0],["2021-12-01T09:15:07",17109.0,0,0,0.0,0,0.0,0],["2021-12-01T09:15:07",17107.1,0,0,0.0,0,0.0,0],["2021-12-01T09:15:08",17110.85,0,0,0.0,0,0.0,0],["2021-12-01T09:15:08",17110.55,0,0,0.0,0,0.0,0],["2021-12-01T09:15:09",17120.9,0,0,0.0,0,0.0,0],["2021-12-01T09:15:09",17119.4,0,0,0.0,0,0.0,0],["2021-12-01T09:15:10",17125.9,0,0,0.0,0,0.0,0],["2021-12-01T09:15:10",17125.9,0,0,0.0,0,0.0,0],["2021-12-01T09:15:11",17128.3,0,0,0.0,0,0.0,0],["2021-12-01T09:15:11",17126.75,0,0,0.0,0,0.0,0],["2021-12-01T09:15:12",17130.45,0,0,0.0,0,0.0,0],["2021-12-01T09:15:12",17129.25,0,0,0.0,0,0.0,0],["2021-12-01T09:15:13",17131.55,0,0,0.0,0,0.0,0],["2021-12-01T09:15:13",17131.4,0,0,0.0,0,0.0,0],["2021-12-01T09:15:14",17134.85,0,0,0.0,0,0.0,0],["2021-12-01T09:15:14",17133.25,0,0,0.0,0,0.0,0],["2021-12-01T09:15:15",17136.65,0,0,0.0,0,0.0,0],["2021-12-01T09:15:15",17135.7,0,0,0.0,0,0.0,0],["2021-12-01T09:15:16",17137.35,0,0,0.0,0,0.0,0],["2021-12-01T09:15:16",17134.85,0,0,0.0,0,0.0,0],["2021-12-01T09:15:17",17135.95,0,0,0.0,0,0.0,0],["2021-12-01T09:15:19",17138.45,0,0,0.0,0,0.0,0],["2021-12-01T09:15:19",17136.0,0,0,0.0,0,0.0,0],["2021-12-01T09:15:20",17140.4,0,0,0.0,0,0.0,0],["2021-12-01T09:15:20",17138.85,0,0,0.0,0,0.0,0],["2021-12-01T09:15:21",17142.8,0,0,0.0,0,0.0,0],["2021-12-01T09:15:21",17138.7,0,0,0.0,0,0.0,0],["2021-12-01T09:15:22",17145.6,0,0,0.0,0,0.0,0],["2021-12-01T09:15:22",17144.35,0,0,0.0,0,0.0,0],["2021-12-01T09:15:23",17147.25,0,0,0.0,0,0.0,0],["2021-12-01T09:15:23",17146.55,0,0,0.0,0,0.0,0],["2021-12-01T09:15:24",17149.6,0,0,0.0,0,0.0,0],["2021-12-01T09:15:24",17149.25,0,0,0.0,0,0.0,0],["2021-12-01T09:15:24",17150.35,0,0,0.0,0,0.0,0],["2021-12-01T09:15:24",17147.15,0,0,0.0,0,0.0,0],["2021-12-01T09:15:25",17147.15,0,0,0.0,0,0.0,0],["2021-12-01T09:15:26",17148.15,0,0,0.0,0,0.0,0],["2021-12-01T09:15:27",17144.65,0,0,0.0,0,0.0,0],["2021-12-01T09:15:28",17142.55,0,0,0.0,0,0.0,0],["2021-12-01T09:15:29",17135.3,0,0,0.0,0,0.0,0],["2021-12-01T09:15:30",17136.45,0,0,0.0,0,0.0,0],["2021-12-01T09:15:31",17134.65,0,0,0.0,0,0.0,0],["2021-12-01T09:15:32",17127.55,0,0,0.0,0,0.0,0],["2021-12-01T09:15:33",17127.3,0,0,0.0,0,0.0,0],["2021-12-01T09:15:34",17126.95,0,0,0.0,0,0.0,0],["2021-12-01T09:15:35",17128.2,0,0,0.0,0,0.0,0],["2021-12-01T09:15:36",17129.55,0,0,0.0,0,0.0,0],["2021-12-01T09:15:37",17130.4,0,0,0.0,0,0.0,0],["2021-12-01T09:15:38",17133.35,0,0,0.0,0,0.0,0],["2021-12-01T09:15:39",17134.2,0,0,0.0,0,0.0,0],["2021-12-01T09:15:40",17136.1,0,0,0.0,0,0.0,0],["2021-12-01T09:15:41",17137.55,0,0,0.0,0,0.0,0],["2021-12-01T09:15:42",17138.3,0,0,0.0,0,0.0,0],["2021-12-01T09:15:43",17145.05,0,0,0.0,0,0.0,0],["2021-12-01T09:15:44",17145.6,0,0,0.0,0,0.0,0],["2021-12-01T09:15:46",17146.3,0,0,0.0,0,0.0,0],["2021-12-01T09:15:47",17148.95,0,0,0.0,0,0.0,0],["2021-12-01T09:15:48",17151.95,0,0,0.0,0,0.0,0],["2021-12-01T09:15:48",17150.2,0,0,0.0,0,0.0,0],["2021-12-01T09:15:49",17152.55,0,0,0.0,0,0.0,0],["2021-12-01T09:15:49",17152.55,0,0,0.0,0,0.0,0],["2021-12-01T09:15:50",17154.35,0,0,0.0,0,0.0,0],["2021-12-01T09:15:50",17153.9,0,0,0.0,0,0.0,0],["2021-12-01T09:15:51",17155.4,0,0,0.0,0,0.0,0],["2021-12-01T09:15:51",17149.45,0,0,0.0,0,0.0,0],["2021-12-01T09:15:52",17157.35,0,0,0.0,0,0.0,0],["2021-12-01T09:15:52",17156.3,0,0,0.0,0,0.0,0],["2021-12-01T09:15:52",17158.3,0,0,0.0,0,0.0,0],["2021-12-01T09:15:52",17155.65,0,0,0.0,0,0.0,0],["2021-12-01T09:15:53",17157.7,0,0,0.0,0,0.0,0]]}
I have to split the record first after that collect all array data inside on it.
You can perhaps use Jackson api to parse it.
implementation 'com.fasterxml.jackson.core:jackson-databind:2.13.0'
then you can use following
String jsonString = "{\"status\":\"Success\",\"Records\":[[\"2021-12-01T09:15:00\",17104.4,0,0,0.0,0,0.0,0],[\"2021-12-01T09:15:00\",17105.05,0,0,0.0,0,0.0,0]]}";
ObjectMapper mapper = new ObjectMapper();
try {
Map map = mapper.readValue(jsonString, Map.class);
List<List> recordsList = (List<List>)map.get("Records");
// Now you can access the elements directly as following
System.out.println(recordsList.get(0).get(0));
} catch (JsonProcessingException e) {
e.printStackTrace();
}
Related
WP Rest API - Post to ACF field?
I'm trying to post to my custom Wordpress field via the REST API from my android app. That said, when I look at the JSON structure of any ACF fields, they're nested inside "acf" like so: { "acf": { "phone_number": "000-0000" } } I'm trying to post a phone number to the phone_number field at my endpoint with the following code/structure, but it won't seem to save? OkHttpClient client = new OkHttpClient(); String url = "http://myurl.com/wp-json/wp/v2/users/loggedinuser/36"; String bearer = "Bearer "; MediaType JSON = MediaType.parse("application/json; charset=utf-8"); JSONObject jsonObject = new JSONObject(); try { jsonObject.put("phone_number", "777-348-4349"); } catch (JSONException e) { e.printStackTrace(); } RequestBody body = RequestBody.create(JSON, jsonObject.toString()); Request request = new Request.Builder() .url(mergeUrl) .method("POST", body) .addHeader("Accept-Charset", "application/json") .addHeader("Authorization", bearer + userToken) .addHeader("Content-Type", "application/json") .build(); Response response = null; try { response = client.newCall(request).execute(); String resStr = response.body().string(); int responseCode = response.code(); if (responseCode == 200) { } else { } } catch (IOException | JSONException e) { e.printStackTrace(); } return null; }} I imagine it's because phone_number is nested inside of "acf". How can I write this line: jsonObject.put("phone_number", "777-348-4349"); so that it matches the structure above? I can't seem to figure out how to nest phone_number inside of the acf value.
Here's how you can nest it to match the structure: JSONObject jsonObject = new JSONObject(); try { JSONObject acf = new JSONObject(); acf.put("phone_number", "777-348-4349"); jsonObject.put("acf", acf); } catch (JSONException e) { e.printStackTrace(); } let me know if this worked for you.
Using ACF with the REST API is explained on this page. To sum it up: You need at least ACF version 5.11 You need to enable the REST API for your field groups The endpoints for users are /users/{user_id} and /users/me (not /users/loggedinuser/{user_id}) The JSON structure is the following: { "acf": { "field": "Value" } }
Why ObjectMapperr does not write values to file?
I wrote a method that gets JSON, converts an object to java and writes JSON to a file.But writing to the file just does not work. Tell me what could be the reason? public class ApiUtils { public static HttpClient client = HttpClient.newHttpClient(); public static void getRequest(String url, String path) { PostDTO postDTO = new PostDTO(); String pathJSONFile = "src/main/resources/Post.json"; List<PostPojo> postPojos = null; HttpRequest request = HttpRequest.newBuilder() .GET() .header("accept", "application/json") .uri(URI.create(url + path)) .build(); try { HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ObjectMapper objectMapper = new ObjectMapper(); postPojos = objectMapper.readValue(response.body(), new TypeReference<List<PostPojo>>() { }); objectMapper.writeValue(Paths.get("allPost.json").toFile(), response.body()); postDTO.setStatus(response.statusCode()); postDTO.setPosts(postPojos); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(postDTO); } } File allPost.json located in the folder resources.
You're writing the wrong object I think - your code sample says objectMapper.writeValue(Paths.get("allPost.json").toFile(), response.body()); which is trying to write the InputStream of response.body(). I presume you meant to try and write out postPojos via objectMapper.writeValue(Paths.get("allPost.json").toFile(), postPojos); instead.
Get response body data for a Network request in DevTools in java
Please help to get the response body(as json) for an intercepted request using Devtools Network. Below is the code I could attempt. Thanks! devTools.addListener(Network.requestWillBeSent(), entry -> { Request req; RequestId rid=entry.getRequestId(); if (entry.getRequest().getUrl().contains("tender")) { req=entry.getRequest(); } try { br.write("Request URI : " + entry.getRequest().getUrl()+"\n With method : "+entry.getRequest().getMethod() + "\n"); } catch (IOException e) {e.printStackTrace();} Command <ResponseBody> resBody=Network.getResponseBody(rid); });
Obviously you're just creating the Command-Object, but not executing and retrieving result. Try this: Command<GetResponseBodyResponse> getBody = Network.getResponseBody(responseReceived.getRequestId()); GetResponseBodyResponse response = driver.getDevTools().send(getBody); ObjectMapper objectMapper = new ObjectMapper(); try { JsonNode n = objectMapper.readValue(response.getBody(), JsonNode.class); debug("Response from Command: " + n.toPrettyString()); } catch (JsonMappingException e) { e.printStackTrace(); } catch (JsonProcessingException e) { e.printStackTrace(); } To get this Response Data I registered ResponseReceived-Event using Network.responseReceived() with your DevTools-Instance.
How to deserialize a generic type with ObjectMapper Jackson
I am struggling trying to simplify my code. I have a common oppperation that makes a request to an API and gets a JSON object. This json can be Categories, Products etc. I am using jackson ObjectMapper. Currently I have a method for each request, but I want to simplify it in one method. For example. myMethod(String Path, Here The class Type) One of this common methods is: public List<Category> showCategories() { HttpClient client = HttpClientBuilder.create().build(); HttpGet getRequest = new HttpGet(Constants.GET_CATEGORY); getRequest.setHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON); getRequest.setHeader(HttpHeaders.COOKIE, Login.getInstance().getToken()); List<Category> data = null; HttpResponse response; try { response = client.execute(getRequest); data = Constants.JSON_MAPPER.readValue(response.getEntity().getContent(), new TypeReference<List<Category>>() { }); } catch (IOException ex) { LOGGER.error("Error retrieving categories, " + ex.toString()); } // TODO: Replace List<category> with Observable? return data; } The one thing that changes across all methods is the type of object to retrieve. It is possible to generalize the line Constants.JSON_MAPPER.readValue(response.getEntity().getContent(), new TypeReference<List<Category>>() { }); To be Constants.JSON_MAPPER.readValue(response.getEntity().getContent(), new TypeReference<List<T>>() { }); I've tried to add as a param to the method Class<T> class, as shown here, but I get the error Cannot find symbol T
I finally came up with a solution, here it is: public static <T> List<T> getList(String url, Class<T> clazz) { HttpClient client = HttpClientBuilder.create().build(); HttpGet getRequest = new HttpGet(url); getRequest.setHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON); getRequest.setHeader(HttpHeaders.COOKIE, Login.getInstance().getToken()); List<T> data = null; HttpResponse response; try { response = client.execute(getRequest); data = Constants.JSON_MAPPER.readValue(response.getEntity().getContent(), Constants.JSON_MAPPER.getTypeFactory().constructCollectionType(List.class, clazz)); } catch (IOException ex) { logger.error("Error retrieving " + clazz.getName() + " " + ex.toString()); } // TODO: Replace List<category> with Observable? return data; }
How to use OKHTTP to make a post request?
I read some examples which are posting jsons to the server. some one says : OkHttp is an implementation of the HttpUrlConnection interface provided by Java. It provides an input stream for writing content and doesn't know (or care) about what format that content is. Now I want to make a normal post to the URL with params of name and password. It means I need to do encode the name and value pair into stream by myself?
As per the docs, OkHttp version 3 replaced FormEncodingBuilder with FormBody and FormBody.Builder(), so the old examples won't work anymore. Form and Multipart bodies are now modeled. We've replaced the opaque FormEncodingBuilder with the more powerful FormBody and FormBody.Builder combo. Similarly we've upgraded MultipartBuilder into MultipartBody, MultipartBody.Part, and MultipartBody.Builder. So if you're using OkHttp 3.x try the following example: OkHttpClient client = new OkHttpClient(); RequestBody formBody = new FormBody.Builder() .add("message", "Your message") .build(); Request request = new Request.Builder() .url("https://www.example.com/index.php") .post(formBody) .build(); try { Response response = client.newCall(request).execute(); // Do something with the response. } catch (IOException e) { e.printStackTrace(); }
The current accepted answer is out of date. Now if you want to create a post request and add parameters to it you should user MultipartBody.Builder as Mime Craft now is deprecated. RequestBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("somParam", "someValue") .build(); Request request = new Request.Builder() .url(BASE_URL + route) .post(requestBody) .build();
private final OkHttpClient client = new OkHttpClient(); public void run() throws Exception { RequestBody formBody = new FormEncodingBuilder() .add("search", "Jurassic Park") .build(); Request request = new Request.Builder() .url("https://en.wikipedia.org/w/index.php") .post(formBody) .build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); System.out.println(response.body().string()); }
You need to encode it yourself by escaping strings with URLEncoder and joining them with "=" and "&". Or you can use FormEncoder from Mimecraft which gives you a handy builder. FormEncoding fe = new FormEncoding.Builder() .add("name", "Lorem Ipsum") .add("occupation", "Filler Text") .build();
You can make it like this: MediaType JSON = MediaType.parse("application/json; charset=utf-8"); RequestBody body = RequestBody.create(JSON, "{"jsonExample":"value"}"); OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(url) .post(body) .addHeader("Authorization", "header value") //Notice this request has header if you don't need to send a header just erase this part .build(); Call call = client.newCall(request); call.enqueue(new Callback() { #Override public void onFailure(Request request, IOException e) { Log.e("HttpService", "onFailure() Request was: " + request); e.printStackTrace(); } #Override public void onResponse(Response r) throws IOException { response = r.body().string(); Log.e("response ", "onResponse(): " + response ); } });
OkHttp POST request with token in header RequestBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("search", "a") .addFormDataPart("model", "1") .addFormDataPart("in", "1") .addFormDataPart("id", "1") .build(); OkHttpClient client = new OkHttpClient(); okhttp3.Request request = new okhttp3.Request.Builder() .url("https://somedomain.com/api") .post(requestBody) .addHeader("token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiIkMnkkMTAkZzZrLkwySlFCZlBmN1RTb3g3bmNpTzltcVwvemRVN2JtVC42SXN0SFZtbzZHNlFNSkZRWWRlIiwic3ViIjo0NSwiaWF0IjoxNTUwODk4NDc0LCJleHAiOjE1NTM0OTA0NzR9.tefIaPzefLftE7q0yKI8O87XXATwowEUk_XkAOOQzfw") .addHeader("cache-control", "no-cache") .addHeader("Postman-Token", "7e231ef9-5236-40d1-a28f-e5986f936877") .build(); client.newCall(request).enqueue(new Callback() { #Override public void onFailure(Call call, IOException e) { e.printStackTrace(); } #Override public void onResponse(Call call, okhttp3.Response response) throws IOException { if (response.isSuccessful()) { final String myResponse = response.body().string(); MainActivity.this.runOnUiThread(new Runnable() { #Override public void run() { Log.d("response", myResponse); progress.hide(); } }); } } });
To add okhttp as a dependency do as follows right click on the app on android studio open "module settings" "dependencies"-> "add library dependency" -> "com.squareup.okhttp3:okhttp:3.10.0" -> add -> ok.. now you have okhttp as a dependency Now design a interface as below so we can have the callback to our activity once the network response received. public interface NetworkCallback { public void getResponse(String res); } I create a class named NetworkTask so i can use this class to handle all the network requests public class NetworkTask extends AsyncTask<String , String, String>{ public NetworkCallback instance; public String url ; public String json; public int task ; OkHttpClient client = new OkHttpClient(); public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); public NetworkTask(){ } public NetworkTask(NetworkCallback ins, String url, String json, int task){ this.instance = ins; this.url = url; this.json = json; this.task = task; } public String doGetRequest() throws IOException { Request request = new Request.Builder() .url(url) .build(); Response response = client.newCall(request).execute(); return response.body().string(); } public String doPostRequest() throws IOException { RequestBody body = RequestBody.create(JSON, json); Request request = new Request.Builder() .url(url) .post(body) .build(); Response response = client.newCall(request).execute(); return response.body().string(); } #Override protected String doInBackground(String[] params) { try { String response = ""; switch(task){ case 1 : response = doGetRequest(); break; case 2: response = doPostRequest(); break; } return response; }catch (Exception e){ e.printStackTrace(); } return null; } #Override protected void onPostExecute(String s) { super.onPostExecute(s); instance.getResponse(s); } } now let me show how to get the callback to an activity public class MainActivity extends AppCompatActivity implements NetworkCallback{ String postUrl = "http://your-post-url-goes-here"; String getUrl = "http://your-get-url-goes-here"; Button doGetRq; Button doPostRq; #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button button = findViewById(R.id.button); doGetRq = findViewById(R.id.button2); doPostRq = findViewById(R.id.button1); doPostRq.setOnClickListener(new View.OnClickListener() { #Override public void onClick(View v) { MainActivity.this.sendPostRq(); } }); doGetRq.setOnClickListener(new View.OnClickListener() { #Override public void onClick(View v) { MainActivity.this.sendGetRq(); } }); } public void sendPostRq(){ JSONObject jo = new JSONObject(); try { jo.put("email", "yourmail"); jo.put("password","password"); } catch (JSONException e) { e.printStackTrace(); } // 2 because post rq is for the case 2 NetworkTask t = new NetworkTask(this, postUrl, jo.toString(), 2); t.execute(postUrl); } public void sendGetRq(){ // 1 because get rq is for the case 1 NetworkTask t = new NetworkTask(this, getUrl, jo.toString(), 1); t.execute(getUrl); } #Override public void getResponse(String res) { // here is the response from NetworkTask class System.out.println(res) } }
This is one of the possible solutions to implementing an OKHTTP post request without a request body. RequestBody reqbody = RequestBody.create(null, new byte[0]); Request.Builder formBody = new Request.Builder().url(url).method("POST",reqbody).header("Content-Length", "0"); clientOk.newCall(formBody.build()).enqueue(OkHttpCallBack());
You should check tutorials on lynda.com. Here is an example of how to encode the parameters, make HTTP request and then parse response to json object. public JSONObject getJSONFromUrl(String str_url, List<NameValuePair> params) { String reply_str = null; BufferedReader reader = null; try { URL url = new URL(str_url); OkHttpClient client = new OkHttpClient(); HttpURLConnection con = client.open(url); con.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream()); writer.write(getEncodedParams(params)); writer.flush(); StringBuilder sb = new StringBuilder(); reader = new BufferedReader(new InputStreamReader(con.getInputStream())); String line; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } reply_str = sb.toString(); } catch (Exception e) { e.printStackTrace(); return null; } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); return null; } } } // try parse the string to a JSON object. There are better ways to parse data. try { jObj = new JSONObject(reply_str); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } return jObj; } //in this case it's NameValuePair, but you can use any container public String getEncodedParams(List<NameValuePair> params) { StringBuilder sb = new StringBuilder(); for (NameValuePair nvp : params) { String key = nvp.getName(); String param_value = nvp.getValue(); String value = null; try { value = URLEncoder.encode(param_value, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } if (sb.length() > 0) { sb.append("&"); } sb.append(key + "=" + value); } return sb.toString(); }
protected Void doInBackground(String... movieIds) { for (; count <= 1; count++) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } Resources res = getResources(); String web_link = res.getString(R.string.website); OkHttpClient client = new OkHttpClient(); RequestBody formBody = new FormBody.Builder() .add("name", name) .add("bsname", bsname) .add("email", email) .add("phone", phone) .add("whatsapp", wapp) .add("location", location) .add("country", country) .add("state", state) .add("city", city) .add("zip", zip) .add("fb", fb) .add("tw", tw) .add("in", in) .add("age", age) .add("gender", gender) .add("image", encodeimg) .add("uid", user_id) .build(); Request request = new Request.Builder() .url(web_link+"edit_profile.php") .post(formBody) .build(); try { Response response = client.newCall(request).execute(); JSONArray array = new JSONArray(response.body().string()); JSONObject object = array.getJSONObject(0); hashMap.put("msg",object.getString("msgtype")); hashMap.put("msg",object.getString("msg")); // Do something with the response. } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return null; }
Here is my method to do post request first pass in method map and data like HashMap<String, String> param = new HashMap<String, String>(); param.put("Name", name); param.put("Email", email); param.put("Password", password); param.put("Img_Name", ""); final JSONObject result = doPostRequest(map,Url); public static JSONObject doPostRequest(HashMap<String, String> data, String url) { try { RequestBody requestBody; MultipartBuilder mBuilder = new MultipartBuilder().type(MultipartBuilder.FORM); if (data != null) { for (String key : data.keySet()) { String value = data.get(key); Utility.printLog("Key Values", key + "-----------------" + value); mBuilder.addFormDataPart(key, value); } } else { mBuilder.addFormDataPart("temp", "temp"); } requestBody = mBuilder.build(); Request request = new Request.Builder() .url(url) .post(requestBody) .build(); OkHttpClient client = new OkHttpClient(); Response response = client.newCall(request).execute(); String responseBody = response.body().string(); Utility.printLog("URL", url); Utility.printLog("Response", responseBody); return new JSONObject(responseBody); } catch (UnknownHostException | UnsupportedEncodingException e) { JSONObject jsonObject=new JSONObject(); try { jsonObject.put("status","false"); jsonObject.put("message",e.getLocalizedMessage()); } catch (JSONException e1) { e1.printStackTrace(); } Log.e(TAG, "Error: " + e.getLocalizedMessage()); } catch (Exception e) { e.printStackTrace(); JSONObject jsonObject=new JSONObject(); try { jsonObject.put("status","false"); jsonObject.put("message",e.getLocalizedMessage()); } catch (JSONException e1) { e1.printStackTrace(); } Log.e(TAG, "Other Error: " + e.getLocalizedMessage()); } return null; }
Add the following to the build.gradle compile 'com.squareup.okhttp3:okhttp:3.7.0' Create a new thread, in the new thread add the following code. OkHttpClient client = new OkHttpClient(); MediaType MIMEType= MediaType.parse("application/json; charset=utf-8"); RequestBody requestBody = RequestBody.create (MIMEType,"{}"); Request request = new Request.Builder().url(url).post(requestBody).build(); Response response = client.newCall(request).execute();
As for Kotlin in 2022 (POST request) works: val client = OkHttpClient() val formBody: RequestBody = MultipartBody.Builder() .addFormDataPart("phone", editText1.text.toString()) .addFormDataPart("email", editText2.text.toString()) .build() val request: Request = Request.Builder() .url("https://hellokitty.com/users") .post(formBody) .build() try { // Do something with the response. val response = client.newCall(request).enqueue(object : Callback { override fun onFailure(call: Call, e: okio.IOException) { print(e.message) } override fun onResponse(call: Call, response: Response) { print(response.message) print("XXX \n" + response.body) } }) editTextResponse.text = response.toString() } catch (e: java.io.IOException) { editTextResponse.text = e.toString() e.printStackTrace() } Gradle: implementation("com.squareup.okhttp3:okhttp:5.0.0-alpha.6") AndroidManifest.xml: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.jaskierltd.blablaApp"> <uses-permission android:name="android.permission.INTERNET"/> ...
If you want to post parameter in okhttp as body content which can be encrypted string with content-type as "application/x-www-form-urlencoded" you can first use URLEncoder to encode the data and then use : final MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("application/x-www-form-urlencoded"); okhttp3.Request request = new okhttp3.Request.Builder() .url(urlOfServer) .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, yourBodyDataToPostOnserver)) .build(); you can add header according to your requirement.
public static JSONObject doPostRequestWithSingleFile(String url,HashMap<String, String> data, File file,String fileParam) { try { final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png"); RequestBody requestBody; MultipartBuilder mBuilder = new MultipartBuilder().type(MultipartBuilder.FORM); for (String key : data.keySet()) { String value = data.get(key); Utility.printLog("Key Values", key + "-----------------" + value); mBuilder.addFormDataPart(key, value); } if(file!=null) { Log.e("File Name", file.getName() + "==========="); if (file.exists()) { mBuilder.addFormDataPart(fileParam, file.getName(), RequestBody.create(MEDIA_TYPE_PNG, file)); } } requestBody = mBuilder.build(); Request request = new Request.Builder() .url(url) .post(requestBody) .build(); OkHttpClient client = new OkHttpClient(); Response response = client.newCall(request).execute(); String result=response.body().string(); Utility.printLog("Response",result+""); return new JSONObject(result); } catch (UnknownHostException | UnsupportedEncodingException e) { Log.e(TAG, "Error: " + e.getLocalizedMessage()); JSONObject jsonObject=new JSONObject(); try { jsonObject.put("status","false"); jsonObject.put("message",e.getLocalizedMessage()); } catch (JSONException e1) { e1.printStackTrace(); } } catch (Exception e) { Log.e(TAG, "Other Error: " + e.getMessage()); JSONObject jsonObject=new JSONObject(); try { jsonObject.put("status","false"); jsonObject.put("message",e.getLocalizedMessage()); } catch (JSONException e1) { e1.printStackTrace(); } } return null; } public static JSONObject doGetRequest(HashMap<String, String> param,String url) { JSONObject result = null; String response; Set keys = param.keySet(); int count = 0; for (Iterator i = keys.iterator(); i.hasNext(); ) { count++; String key = (String) i.next(); String value = (String) param.get(key); if (count == param.size()) { Log.e("Key",key+""); Log.e("Value",value+""); url += key + "=" + URLEncoder.encode(value); } else { Log.e("Key",key+""); Log.e("Value",value+""); url += key + "=" + URLEncoder.encode(value) + "&"; } } /* try { url= URLEncoder.encode(url, "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); }*/ Log.e("URL", url); OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(url) .build(); Response responseClient = null; try { responseClient = client.newCall(request).execute(); response = responseClient.body().string(); result = new JSONObject(response); Log.e("response", response+"=============="); } catch (Exception e) { JSONObject jsonObject=new JSONObject(); try { jsonObject.put("status","false"); jsonObject.put("message",e.getLocalizedMessage()); return jsonObject; } catch (JSONException e1) { e1.printStackTrace(); } e.printStackTrace(); } return result; }