Android开发(使用Java)中 client.newCall(request).execute() 语句永久阻塞的问题

小白,开发安卓的小型app,希望使用http的post方法向云端服务器发送json文件,然后获取云端返回的json,以此实现相关操作(比如向服务器发送包含用户名和密码的json文件,然后接收返回的json文件,解析,决定是否允许登录)

由于楼主是学生,暂时付不起云主机的钱,所以和同伴一起在局域网内建立了一个服务器用来前期进行调试。可是在编写android端代码的时候,遇到了问题,就是老是阻塞在一个地方:execute()

下面是代码:

   //访问云端服务器,获得登录授权
    private boolean getAuthorization() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //创建Client对象
                    Log.d(debugTag, "创建Client对象");
                    OkHttpClient client = new OkHttpClient();
                    //创建request对象
                    Log.d(debugTag, "创建request对象");
                    Request request = new Request.Builder()
                            .url("http://10.0.2.2/data")
                            .build();
                    //创建response对象
                    Log.d(debugTag, "创建response对象");
                    Response response = client.newCall(request).execute();
                    //获取返回值
                    Log.d(debugTag, "获取返回值");
                    String data = response.body().string();
                    //打印
                }catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
        return false;
    }

这里同伴不在身边,所以就暂时在我电脑上用Apache搭了一个localhost

文件结构:

图片说明

data文件的内容:{ "UserName":"John" , "PassWord":"123123" }

用电脑访问的结果:

图片说明

用Postman访问结果:
图片说明
用手机模拟器的浏览器访问结果:

图片说明

都是没有问题的
但是用我自己写的代码访问就不行(上面代码在Android Studio的日志窗口的运行结果):
图片说明

可以发现只运行到了“创建response对象”那一步,之后的execute()永远阻塞住了

但是改一下上面代码的url,改成"https://api.github.com/markdown/raw"
运行就正常了!

图片说明
我的电脑防火墙已经全部关闭

2个回答

好吧,我们组这几天时间特紧,又不是这个专业的,没有必要花太大功夫。我就自问自答取消这个问题吧。

qq_40761869
vute 回复qq_44723229: 我解决了,是因为android不支持http访问方式,必须修改配置或者改成https访问方式
9 个月之前 回复
qq_44723229
qq_44723229 回复vute: 我也是遇到这个问题,请问楼主最后解决了吗
10 个月之前 回复
qq_40761869
vute 你好,谢谢回答,不过他的问题跟我遇到的不一样啊。我是execute()这一步都过不去,而那个帖子里写的是execute()之后的解析出席那问题。麻烦仔细看看。
大约一年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
okhttp抛出, Response response = client.newCall(request).execute();报错,该怎么解决

``` try { MediaType JSON = MediaType.parse("application/json; charset=utf-8"); OkHttpClient client = new OkHttpClient(); RequestBody body = RequestBody.create(JSON,ObjToJson.tojson(user)); Request request = new Request.Builder() .addHeader("Connection","close") .url(Location.login) .post(body) .build(); Log.v("url",Location.login); Log.v("body",body.toString()); Response response = client.newCall(request).execute(); if (response.isSuccessful()) { User user2= JsonToObj.toUser(response.body().toString()); Toast.makeText(LoginActivity.this,user2.getTel(),Toast.LENGTH_SHORT).show(); }else{ new Exception("Unexpected code " + response); } } catch (Exception e) { e.printStackTrace(); } ``` ``` V/url: http://120.79.146.32:8080/EasyToCreat2.0/User/login.action V/body: okhttp3.RequestBody$2@90bbbec W/System.err: android.os.NetworkOnMainThreadException W/System.err: at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1448) at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:355) W/System.err: at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200) at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:356) at java.net.Socket.connect(Socket.java:616) at okhttp3.internal.Platform$Android.connectSocket(Platform.java:211) at okhttp3.internal.io.RealConnection.connectSocket(RealConnection.java:140) at okhttp3.internal.io.RealConnection.connect(RealConnection.java:111) W/System.err: at okhttp3.internal.http.StreamAllocation.findConnection(StreamAllocation.java:188) at okhttp3.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:127) at okhttp3.internal.http.StreamAllocation.newStream(StreamAllocation.java:97) at okhttp3.internal.http.HttpEngine.connect(HttpEngine.java:289) at okhttp3.internal.http.HttpEngine.sendRequest(HttpEngine.java:241) at okhttp3.RealCall.getResponse(RealCall.java:240) at okhttp3.RealCall$ApplicationInterceptorChain.proceed(RealCall.java:198) at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:160) at okhttp3.RealCall.execute(RealCall.java:57) W/System.err: at com.example.easytocreate.LoginActivity$button_login_loginClick.onClick(LoginActivity.java:60) at android.view.View.performClick(View.java:6256) at android.view.View$PerformClick.run(View.java:24701) at android.os.Handler.handleCallback(Handler.java:789) at android.os.Handler.dispatchMessage(Handler.java:98) at android.os.Looper.loop(Looper.java:164) at android.app.ActivityThread.main(ActivityThread.java:6541) W/System.err: at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) ```

求大神看看代码,帮帮我

public void onClick(View view) { new Thread(new Runnable() { @Override public void run() { try { String username = usernameEdit.getText().toString(); String password = passwordEdit.getText().toString(); OkHttpClient client = new OkHttpClient(); RequestBody requestBody = new FormBody.Builder() .add("username", username) .add("password", password) .build(); Request request = new Request.Builder() .url("http://test.ourwechat.com/test/auth.php") .post(requestBody) .build(); Response response = client.newCall(request).execute(); String responseData = response.body().string(); JSONObject object = new JSONObject(responseData); code = object.getInt("code"); if (code ==-1){ Toast.makeText(Login.this,"登录失败",Toast.LENGTH_SHORT).show(); }else if (code == 1){ Intent home = new Intent(Login.this, Homepage.class); startActivity(home); } } catch (JSONException e) { e.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } } }).start(); 以上是代码 以下是错误日志 java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare() at android.os.Handler.<init>(Handler.java:200) at android.os.Handler.<init>(Handler.java:114) at android.widget.Toast$TN.<init>(Toast.java:348) at android.widget.Toast.<init>(Toast.java:101) at android.widget.Toast.makeText(Toast.java:260) at com.money.Login.Login$1$1.run(Login.java:90) at java.lang.Thread.run(Thread.java:761) 求大神指出问题

android客户端okhttp连接服务器问题!急!

public void login(View view) { String url = "http://10.0.2.2/myserver_war_exploded/userLogin.html"; String username= ((EditText)findViewById(R.id.username)).getText().toString();//获取用户名 String password = ((EditText)findViewById(R.id.password)).getText().toString();//获取密码 OkHttpClient client = new OkHttpClient(); //创建RequestBody对象,添加参数 RequestBody requestBody = new FormBody.Builder().add("username",username).add("password",password).build(); //创建post方法的request对象 Request request = new Request.Builder().post(requestBody).url(url).build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { if (e instanceof ConnectException) { Log.e("frost_connection",e.getMessage()); System.out.println("fail1"); } System.out.println("fail2"); } @Override public void onResponse(Call call, Response response) throws IOException { if(response.isSuccessful()) { System.out.println("连接成功"); } } }); } 无论如何都是onfailure,在avd虚拟机中直接浏览器访问10.0.2.2也进不去,求懂android客户端和服务器端的大神解答。 后台服务器也是本机实现,昨天尝试时请求可以用服务器接受,今天不行了。服务器端没有问题,使用电脑浏览器可以访问。贴上昨天尝试成功的解决方案: manifests添加了: <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> application标签中添加了: android:usesCleartextTraffic="true"

使用OKhttp3将图像上传到服务器失败

<div class="post-text" itemprop="text"> <p>我使用OKhttp 3来处理网络请求,并试图将图像上传到服务器。这是我试过的方式,但不管用。哪里出错了?</p> <pre><code>public void upload(String url, String filePath) throws java.io.IOException { java.io.File file = new File(filePath); okhttp3.OkHttpClient client = new okhttp3.OkHttpClient(); okhttp3.RequestBody formBody = new okhttp3.MultipartBody.Builder() .setType(okhttp3.MultipartBody.FORM) .addFormDataPart("file", file.getName(), okhttp3.RequestBody.create(okhttp3.MediaType.parse("text/plain"), file)) .addFormDataPart("other_field", "other_field_value") .build(); okhttp3.Request request = new okhttp3.Request.Builder().url(url).post(formBody).build(); okhttp3.Response response = client.newCall(request).execute(); } </code></pre> <p>这是我的PHP代码:</p> <pre><code>&lt;?php $uploaddir = '/uploads/'; $uploadfile = $uploaddir . basename($_FILES['file']['name']); echo "&lt;p&gt;"; if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) { echo "File is valid, and was successfully uploaded. "; } else { echo "Upload failed"; } echo "&lt;/p&gt;"; echo '&lt;pre&gt;'; echo 'Here is some more debugging info:'; print_r($_FILES); print "&lt;/pre&gt;"; ?&gt; </code></pre> </div>

使用Java和PHP通过okhttp进行JSON请求

<div class="post-text" itemprop="text"> <p>I am using okhttp lib with Java and PHP. My Java client is running the following code.</p> <pre><code>public class Connection { public static final MediaType JSON = MediaType .parse("application/json; charset=utf-8"); OkHttpClient client = new OkHttpClient(); String post(String url, String json) 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(); } public static void main(String[] args) throws IOException { Connection example = new Connection(); String json = "{'input':'test'}"; String response = example.post("http://localhost/android_api/index.php", json); System.out.println(response); } } </code></pre> <p>On the server-side I try to decode the JSON String with code following below but my webservice just return a NULL. </p> <pre><code>&lt;?php $rawData = file_get_contents("php://input"); $json = json_decode($rawData); var_dump($json); ?&gt; </code></pre> <p>What am I doint wrong?</p> </div>

ANDROID - 如何在android studio中将数据库mysql php的值显示到textview中

<div class="post-text" itemprop="text"> <p>I've been looking some references to display my value database into android using JSON, but i have a trouble about the keyword to find it, here is all my code to try, please CMIIW, i have put my code and DB into hostinger to make it easy <a href="http://zxccvvv.cuccfree.com/" rel="nofollow">here</a></p> <h1>php code</h1> <blockquote> <p>dbconfig.php</p> </blockquote> <pre><code>$servername = "localhost"; $username = "root"; $password = ""; $dbname = "data_kuesioner"; </code></pre> <blockquote> <p>send_data.php</p> </blockquote> <pre><code>&lt;?php include 'dbconfig.php'; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn-&gt;connect_error) { die("Connection failed: " . $conn-&gt;connect_error); } $sql = "SELECT * FROM pertanyaan"; $result = $conn-&gt;query($sql); if ($result-&gt;num_rows &gt; 0) { while($row[] = $result-&gt;fetch_assoc()) { $json = json_encode($row); } } else { echo "0 results"; } echo $json; $conn-&gt;close(); ?&gt; </code></pre> <h1>android code</h1> <blockquote> <p>MainActivity.java</p> </blockquote> <pre class="lang-js prettyprint-override"><code>package flix.yudi.okhttp; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.TextView; import java.io.IOException; import java.util.concurrent.ExecutionException; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; public class MainActivity extends AppCompatActivity { private EditText edtText; private TextView outputText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); edtText = (EditText) findViewById(R.id.editText1); outputText = (TextView) findViewById(R.id.textView1); } public void downloadUrl(View view) { String url = "http://" + edtText.getText().toString(); OkHttpHandler handler = new OkHttpHandler(); String result = null; try { result = handler.execute(url).get(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); } outputText.append(result + " "); } } </code></pre> <blockquote> <p>OkHttpHandler.java</p> </blockquote> <pre class="lang-js prettyprint-override"><code>package flix.yudi.okhttp; import android.os.AsyncTask; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class OkHttpHandler extends AsyncTask&lt;String, Void, String&gt; { OkHttpClient client = new OkHttpClient(); @Override protected String doInBackground(String... params) { Request.Builder builder = new Request.Builder(); builder.url(params[0]); Request request = builder.build(); try { Response response = client.newCall(request).execute(); return response.body().string(); } catch (Exception e) { } return null; } } </code></pre> <p>but when i run the program, the app display another interface below</p> <p><a href="https://i.stack.imgur.com/1uyLX.png" rel="nofollow"><img src="https://i.stack.imgur.com/1uyLX.png" alt="Pic"></a></p> </div>

正在学习android的第一行代码的coolweather遇到了点问题

ChooseAreaFragment代码 import android.app.ProgressDialog; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.widget.ButtonBarLayout; import androidx.fragment.app.Fragment; import com.example.coolweather.db.City; import com.example.coolweather.db.County; import com.example.coolweather.db.Province; import com.example.coolweather.util.HttpUtil; import com.example.coolweather.util.Utility; import org.litepal.crud.DataSupport; import java.io.IOException; import java.util.ArrayList; import java.util.List; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; public class ChooseAreaFrament extends Fragment { public static final int LEVEL_PROVINCE = 0; public static final int LEVEL_CITY=1; public static final int LEVEL_COUNTY = 2; private ProgressDialog progressDialog; private TextView titleText; private Button backButton; private ListView listView; private ArrayAdapter<String> adapter; private List<String> dataList = new ArrayList<>(); /** * 省列表 */ private List<Province> provinceList; /** * 市列表 */ private List<City> cityList; /** * 县列表 */ private List<County>countyList; /** * 选中的省份 */ private Province selectedProvince; /** * 选中的城市 */ private City selectedCity; /** * 当前选中的级别 */ private int currentLevel; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.choose_area,container,false); titleText = (TextView) view.findViewById(R.id.title_text); backButton = (Button) view.findViewById(R.id.back_button); listView = (ListView)view.findViewById(R.id.list_view); adapter = new ArrayAdapter<>(getContext(),android.R.layout.simple_list_item_1,dataList); listView.setAdapter(adapter); return view; } @Override public void onActivityCreated(Bundle savedInstanceState){ super.onActivityCreated(savedInstanceState); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if(currentLevel == LEVEL_PROVINCE){ selectedProvince = provinceList.get(position); queryCities(); } else if (currentLevel == LEVEL_CITY) { selectedCity = cityList.get(position); queryCounties(); } } }); backButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (currentLevel == LEVEL_COUNTY) { queryCities(); } else if (currentLevel == LEVEL_CITY){ queryProvinces(); } } }); queryProvinces(); } /** * 查询全国所有的省,优先数据库查询,如果没有查询到再去服务器上查询 */ private void queryProvinces(){ titleText.setText("中国"); backButton.setVisibility(View.GONE); provinceList = DataSupport.findAll(Province.class); if (provinceList.size() > 0){ dataList.clear(); for (Province province : provinceList){ dataList.add(province.getProvinceName()); } adapter.notifyDataSetChanged(); listView.setSelection(0); currentLevel = LEVEL_PROVINCE; } else { String address = "http://guolin.tech/api/china"; queryFromServer(address,"province"); } } /** * 查询全国所有的城市,优先数据库查询,如果没有查询到再去服务器上查询 */ private void queryCities(){ titleText.setText(selectedProvince.getProvinceName()); backButton.setVisibility(View.VISIBLE); cityList = DataSupport.where("provinceid = ?",String.valueOf(selectedProvince. getId())).find(City.class); if(cityList.size() > 0){ dataList.clear(); for(City city : cityList){ dataList.add(city.getCityName()); } adapter.notifyDataSetChanged(); listView.setSelection(0); currentLevel = LEVEL_CITY; }else{ int provinceCode = selectedProvince.getProvinceCode(); String address = "http://guolin.tech/api/china/" + provinceCode; queryFromServer(address,"city"); } } /** * 查询全国所有的县,优先数据库查询,如果没有查询到再去服务器上查询 */ private void queryCounties(){ titleText.setText(selectedCity.getCityName()); backButton.setVisibility(View.VISIBLE); countyList = DataSupport.where("cityid = ?",String.valueOf(selectedCity. getId())).find(County.class); if(countyList.size() > 0 ){ dataList.clear(); for(County county : countyList){ dataList.add(county.getCountyName()); } adapter.notifyDataSetChanged(); listView.setSelection(0); currentLevel = LEVEL_COUNTY; }else{ int provinceCode = selectedProvince.getProvinceCode(); int cityCode = selectedCity.getCityCode(); String address = "http://guolin.tech/api/china/" + provinceCode + "/" + cityCode; queryFromServer(address,"county"); } } /** * 根据传入的地址和类型从服务器上查询省市县数据 */ private void queryFromServer(String address,final String type){ showProgressDialog(); HttpUtil.sendOkHttpRequest(address, new Callback() { @Override public void onResponse(Call call, Response response) throws IOException { String responseText = response.body().string(); boolean result = false; if("province".equals(type)){ result = Utility.handleProvinceResponse(responseText); } else if ("city".equals(type)){ result = Utility.handleCityResponse(responseText,selectedProvince.getId()); } else if ("county".equals(type)){ result = Utility.handleCountyResponse(responseText,selectedCity.getId()); } if (result){ getActivity().runOnUiThread(new Runnable() { @Override public void run() { closeProgressDialog(); if ("province".equals(type)){ queryProvinces(); } else if ("city".equals(type)){ queryCities(); } else if ("county".equals(type)) queryCounties(); } }); } } @Override public void onFailure(Call call, IOException e) { //通过runOnUiTread()方法回到主线程处理逻辑 getActivity().runOnUiThread(new Runnable() { @Override public void run() { closeProgressDialog(); Toast.makeText(getContext(),"加载失败",Toast.LENGTH_SHORT).show(); } }); } }); } /** * 显示进度对话框 */ private void showProgressDialog(){ if (progressDialog == null){ progressDialog = new ProgressDialog(getActivity()); progressDialog.setMessage("正在加载..."); progressDialog.setCanceledOnTouchOutside(false); } progressDialog.show(); } /** * 关闭进度对话框 */ private void closeProgressDialog(){ if (progressDialog != null){ progressDialog.dismiss(); } } Utility代码 import android.text.TextUtils; import com.example.coolweather.db.City; import com.example.coolweather.db.County; import com.example.coolweather.db.Province; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class Utility { /** * 解析和处理服务器返回的省级数据 */ public static boolean handleProvinceResponse(String response){ if (!TextUtils.isEmpty(response)){ try { JSONArray allProvinces = new JSONArray(response); for (int i = 0;i<allProvinces.length();i++){ JSONObject provinceObject = allProvinces.getJSONObject(i); Province province = new Province(); province.setProvinceName(provinceObject.getString("name")); province.setProvinceCode(provinceObject.getInt("id")); province.save(); } return true; } catch (JSONException e) { e.printStackTrace(); } } return false; } /** * 解析服务器和处理器返回的市级数据 */ public static boolean handleCityResponse(String response,int provinceId){ if(!TextUtils.isEmpty(response)){ try { JSONArray allCities = new JSONArray(response); for(int i=0;i<allCities.length();i++){ JSONObject cityObject = allCities.getJSONObject(i); City city = new City(); city.setCityName(cityObject.getString("name")); city.setCityCode(cityObject.getInt("id")); city.setProvinceId(provinceId); city.save(); } return true; } catch (JSONException e) { e.printStackTrace(); } } return false; } public static boolean handleCountyResponse(String response, int cityId){ if(TextUtils.isEmpty(response)){ try { JSONArray allCounties = new JSONArray(response); for(int i=0;i<allCounties.length();i++){ JSONObject countyObject = allCounties.getJSONObject(i); County county = new County(); county.setCountyName(countyObject.getString("name")); county.setWeatherId(countyObject.getString("weather_id")); county.setCityId(cityId); county.save(); } return true; } catch (JSONException e) { e.printStackTrace(); } } return false; } 复制代码 } HttpUtil代码 import okhttp3.OkHttpClient; import okhttp3.Request; public class HttpUtil { public static void sendOkHttpRequest(String address,okhttp3.Callback callback) { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(address).build(); client.newCall(request).enqueue(callback); } 复制代码 } app apply plugin: 'com.android.application' android { compileSdkVersion 29 buildToolsVersion "29.0.2" defaultConfig { applicationId "com.example.coolweather" minSdkVersion 15 targetSdkVersion 29 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } sourceSets { main { jniLibs.srcDirs = ['libs'] } } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'androidx.appcompat:appcompat:1.0.2' implementation 'androidx.constraintlayout:constraintlayout:1.1.3' implementation 'org.litepal.android:core:1.4.1' implementation 'com.squareup.okhttp3:okhttp:3.4.1' implementation 'com.google.code.gson:gson:2.7' implementation 'com.github.bumptech.glide:glide:3.7.0' testImplementation 'junit:junit:4.12' androidTestImplementation 'androidx.test:runner:1.2.0' androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0' } debug到这里就动不了![图片说明](https://img-ask.csdn.net/upload/201908/14/1565753464_912183.png)

使用PhP在android和mysql之间建立连接时出错

<div class="post-text" itemprop="text"> <p>I am creating a app which will show the data of MySQL table in the card_layout of the android app.</p> <p>The below mentioned is the connection code in MainActivity.java</p> <pre><code>private void load_data_from_server(final int id) { AsyncTask&lt;Integer,Void,Void&gt; task = new AsyncTask&lt;Integer, Void, Void&gt;() { @RequiresApi(api = Build.VERSION_CODES.KITKAT) @Override protected Void doInBackground(Integer... params) { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url("http://10.10.2.2/develop/php_recyler_demo.php?id="+id).build(); try { Response response = client.newCall(request).execute(); JSONArray array = new JSONArray(response.body().toString()); for (int i=0; i&lt;array.length(); i++) { JSONObject object = array.getJSONObject(i); MyData data = new MyData(object.getInt("id"),object.getString("description"),object.getString("image")); data_list.add(data); } } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void aVoid) { adapter.notifyDataSetChanged(); } }; task.execute(id); } </code></pre> <p>For the MySQL connection I am using PhP and executing in the <code>XAMPP</code> server as <code>localhost</code>, the code is as follows:</p> <pre><code>&lt;?php $connection = mysqli_connect("localhost","root","","test"); //$id = $_GET["id"]; $id = isset($_GET['id']) ? $_GET['id'] : ''; $query = "select * from recyclerdb where id between ($id+1) and ($id+4)"; $result = mysqli_query($connection,$query); while ($row = mysqli_fetch_assoc($result)) { # code... $array[] = $row; } header('Content-type:Application/json'); echo json_encode($array); ?&gt; </code></pre> <p>My table structure is as follows: <a href="https://i.stack.imgur.com/81fo9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/81fo9.png" alt="The table structure"></a></p> <p>When I run this PhP file using browser then I am getting correct output as <code>JSON array</code>:<a href="https://i.stack.imgur.com/4nyfP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4nyfP.png" alt="Image for the output of PhP file in browser"></a></p> <p>But if I execute my app in android studio using emulator</p> <p>I am getting <code>java.net.SocketTimeoutException: connect timed out</code></p> <p>The problem I am getting at the two lines of <code>MainActivity.java</code>:</p> <p><code>AsyncTask&lt;Integer,Void,Void&gt; task = new AsyncTask&lt;Integer, Void, Void&gt;()</code></p> <p><code>Response response = client.newCall(request).execute();</code></p> <p>I did research for a long time, please someone help me out.</p> </div>

okhttp与远程服务器通信不上,本地服务器可以通信

在做安卓客户端和python服务端的通信。在app上输入用户名和密码发给服务端,我在本地运行py文件可以实现通信。但是我把py文件传到服务器上启动就不能返回结果。请教各位大神,初次接触这方面。 服务端用的简单的flask,代码如下 ``` from flask import Flask from flask import request import os app = Flask(__name__) @app.route('/') def test(): return '服务器正常运行' #此方法处理用户注册 @app.route('/register',methods=['POST']) def register(): username=request.form['username'] password=request.form['password'] print('username:'+username) print('password:'+password) return '注册成功' if __name__ == '__main__': app.run(host='0.0.0.0') ``` Android的代码: ``` private void SendMessage(String url, final String userName, String passWord) { OkHttpClient client = new OkHttpClient(); FormBody.Builder formBuilder = new FormBody.Builder(); formBuilder.add("username", userName); formBuilder.add("password", passWord); Request request = new Request.Builder().url(url).post(formBuilder.build()).build(); Call call = client.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { runOnUiThread(new Runnable() { @Override public void run() { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(MainActivity.this, "服务器错误", Toast.LENGTH_SHORT).show(); } }); } }); } @Override public void onResponse(Call call, final Response response) throws IOException { final String res = response.body().string(); System.out.println("3333333333333333333"); runOnUiThread(new Runnable() { @Override public void run() { if (res.equals("0")) { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(MainActivity.this, "该用户名已被注册", Toast.LENGTH_SHORT).show(); } }); } else { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(MainActivity.this, "成功", Toast.LENGTH_SHORT).show(); } }); } } }); } }); ```

为什么我不从OkHttp3收到POST变量? (Android Studio)

<div class="post-text" itemprop="text"> <p>I've answered my own question here. See the first code block where I use php://input to get the posted data.</p> <p>I'm trying to send a post request from my app to a webserver, and I'm checking for the post vars using PHP:</p> <pre><code>if( isset( $_POST['name'] ) ){ echo json_encode(['status' =&gt; 1]); }else if( $posted_data = (string) @file_get_contents('php://input') ) { echo json_encode(['status' =&gt; 2]); }else{ echo json_encode($_POST); } </code></pre> <p>The request always returns and empty json encoded array.</p> <p>I'm using the latest Android Studio, and the latest OkHttp, com.squareup.okhttp3:okhttp:3.4.1. For me, this is like the "Hello World" of OkHttp in Android Studio.</p> <p>In MainActivity.java:</p> <pre><code>public void postSomething(View view) { String url = "https://example.com/json_api_test.php"; String json = "{\"name\":\"cholula\"}"; OkHttpPostHandler handler = new OkHttpPostHandler(); String result = ""; try { result = handler.execute(url, json).get(); } catch (Exception e) { e.printStackTrace(); } displayPostResponse(result + " "); } </code></pre> <p>My OkHttpPostHandler.java:</p> <pre><code>public class OkHttpPostHandler extends AsyncTask&lt;String, Void, String&gt; { OkHttpClient client = new OkHttpClient(); public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); @Override protected String doInBackground(String... params) { RequestBody body = RequestBody.create(JSON, params[1]); Request request = new Request.Builder() .url(params[0]) .post(body) .build(); try { Response response = client.newCall(request).execute(); return response.body().string(); } catch( Exception e ){ return "HTTP Request Error"; } } } </code></pre> <p>When I debug, I can see that the params[1] value is the expected json-like string, but that's the last time I see it.</p> <p>I've tried forming the json in a number of ways, so I'm not sure if that's the problem. I just don't understand why I can't see the posted vars when the post request gets to the server.</p> <p>How can I see the posted vars on the webserver? What am I doing wrong? I've only been using Android Studio and Java for less than a week, so I have no clue. I've really looked around the internet a lot for the answer, and so posting here is the last resort.</p> <p>Thanks!</p> </div>

关于安卓内存泄露的问题

小弟最近在做一个小项目,基本上功能完成了,但发现在程序运行了几分钟后会自动退出,打印的日志信息如下: ![图片说明](https://img-ask.csdn.net/upload/201907/22/1563795606_231565.png) 然后又通过对程序进行注释后发现在将从服务器获取数据的功能注释掉后这个问题解决了,所以觉得问题应该是出在这一块,在这个功能中循环调用的函数有关于对象以及线程,不知是否是这一块的问题,现将整个程序贴上求大神帮忙看看: MainActivity中: ``` package com.example.gsontest; import android.Manifest; import android.content.pm.PackageManager; import android.os.Bundle; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.widget.Toast; import com.baidu.location.BDLocation; import com.baidu.location.BDLocationListener; import com.baidu.location.LocationClient; import com.baidu.location.LocationClientOption; import com.baidu.mapapi.SDKInitializer; import com.baidu.mapapi.map.BaiduMap; import com.baidu.mapapi.map.BitmapDescriptor; import com.baidu.mapapi.map.BitmapDescriptorFactory; import com.baidu.mapapi.map.MapStatusUpdate; import com.baidu.mapapi.map.MapStatusUpdateFactory; import com.baidu.mapapi.map.MapView; import com.baidu.mapapi.map.MarkerOptions; import com.baidu.mapapi.map.MyLocationConfiguration; import com.baidu.mapapi.map.MyLocationData; import com.baidu.mapapi.map.OverlayOptions; import com.baidu.mapapi.model.LatLng; import com.baidu.mapapi.utils.CoordinateConverter; import org.json.JSONObject; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class MainActivity extends AppCompatActivity { private MapView mapView; private BaiduMap baiduMap; public LocationClient mLocationClient; public static String responseData; public double dvalueX; public double dvalueY; private boolean isFirstLocate = true; public int mXDirection; //方向类的对象 public MyOrientationListener myOrientationListener; @Override //该函数主要是进行Activity初始化 protected void onCreate(Bundle savedInstanceState) { Log.i("MainActivity","进入到onCreate函数中进行初始化"); super.onCreate(savedInstanceState); //实例化对象 mLocationClient = new LocationClient(getApplicationContext()); //注册监听器 mLocationClient.registerLocationListener(new MyLocationListener()); //初始化SDK SDKInitializer.initialize(getApplicationContext()); setContentView(R.layout.activity_main); mapView = (MapView) findViewById(R.id.bmpView); baiduMap = mapView.getMap(); baiduMap.setMyLocationEnabled(true); //尝试在监听按钮之前进行权限的允许 List<String> permissionList = new ArrayList<>(); if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION); } if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) { permissionList.add(Manifest.permission.READ_PHONE_STATE); } if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE); } if (!permissionList.isEmpty()) { String[] permission = permissionList.toArray(new String[permissionList.size()]); ActivityCompat.requestPermissions(MainActivity.this, permission, 1); requestLocation(); } else { requestLocation(); } } private void requestLocation() { Log.i("MainActivity", "进入到requestLocation函数中"); initLocation(); //定位开始 initOrientationListener(); myOrientationListener.start(); mLocationClient.start(); } private void initLocation() { Log.i("MainActivity", "跳进了initLocation定位初始化函数中"); LocationClientOption option = new LocationClientOption(); option.setCoorType("bd09ll"); option.setScanSpan(1000); mLocationClient.setLocOption(option); } private void initOrientationListener() { Log.i("MainActivity", "跳进了initOrientationListener方向初始化函数中"); myOrientationListener = new MyOrientationListener(getApplicationContext()); myOrientationListener.setOnOrientationListener(new MyOrientationListener.OnOrientationListener() { @Override public void onOrientationChanged(float x) { mXDirection = (int) x; } }); } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { Log.i("MainActivityActivity","进入onRequestPermissionResult函数中"); switch (requestCode) { case 1: if (grantResults.length > 0) { for (int result : grantResults) { if (result != PackageManager.PERMISSION_GRANTED) { Toast.makeText(this, "必须同意所有权限", Toast.LENGTH_LONG).show(); finish(); return; } } // sendRequestWithOkHttp(); } else { Toast.makeText(this, "发生未知错误", Toast.LENGTH_LONG).show(); finish(); } break; default: } } //定位监听器的类 public class MyLocationListener implements BDLocationListener { @Override public void onReceiveLocation(BDLocation location) { Log.i("MainActivity", "跳进了onReceiveLocation函数中"); if (location.getLocType() == BDLocation.TypeGpsLocation || location.getLocType() == BDLocation.TypeNetWorkLocation) { navigateTo(location); } } } private void navigateTo(BDLocation location) { Log.i("MainActivity", "跳进了navigateTo函数中"); //从服务器上获取实时的硬件位置 sendRequestWithOkHttp(); //将获取到的数据进行解析 ObjectJson(responseData); //将获取到的经纬度信息在地图上进行显示 displayLocation(dvalueX, dvalueY); //初次定位确定缩放尺寸,后面不改变便于手动伸缩 if (isFirstLocate) { BitmapDescriptor myBitMap = BitmapDescriptorFactory.fromResource(R.drawable.icon_reddirection); MyLocationConfiguration myLocationConfiguration = new MyLocationConfiguration(MyLocationConfiguration.LocationMode.NORMAL, true, myBitMap); baiduMap.setMyLocationConfiguration(myLocationConfiguration); LatLng la = new LatLng(location.getLatitude(), location.getLongitude()); MapStatusUpdate update = MapStatusUpdateFactory.newLatLng(la); baiduMap.animateMapStatus(update); update = MapStatusUpdateFactory.zoomTo(18f); baiduMap.animateMapStatus(update); isFirstLocate = false; } //将手机当前位置的小蓝点显示在屏幕上 MyLocationData.Builder locationBuilder = new MyLocationData.Builder(); locationBuilder.latitude(location.getLatitude()); locationBuilder.longitude(location.getLongitude()); //将要执行获取方向方法 locationBuilder.direction(mXDirection); MyLocationData locationData = locationBuilder.build(); baiduMap.setMyLocationData(locationData); } //重写三个方法以对mapView进行管理,保证资源可以及时释放 @Override protected void onResume() { Log.i("MainActivity", "进入到onResume函数中"); super.onResume(); mapView.onResume(); } @Override protected void onPause() { Log.i("MainActivity", "进入到onPause函数中"); super.onPause(); mapView.onPause(); } @Override protected void onDestroy() { Log.i("MainActivity", "进入到onDestroy函数中"); super.onDestroy(); mapView.onDestroy(); baiduMap.setMyLocationEnabled(false); mLocationClient.stop(); //停止方向监听 myOrientationListener.stop(); } private void sendRequestWithOkHttp() { Log.i("MainActivity", "跳进了sendRequestWithOkHttp方法中"); new Thread(new Runnable() { @Override //重写run方法,run方法规定了该线程的具体使命 public void run() { Log.i("MainActivity","跳进OkHttp的子线程中"); try { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url("https://huadiheal.cn/animal/latest_data") .build(); Response response = client.newCall(request).execute(); responseData = response.body().string(); // ObjectJson(responseData); } catch (Exception e) { e.printStackTrace(); } } //创建后线程仅是占有内存资源,在JVM管理的线程中还没有这个资源,要调用父类的start方法通知JVM }).start(); } private void ObjectJson(String responseData) { Log.i("MainActivity", "跳进了ObjectJson函数中"); try { JSONObject jsonObject = new JSONObject(responseData); JSONObject valueX = jsonObject.getJSONObject("value_x"); JSONObject valueY = jsonObject.getJSONObject("value_y"); Iterator<String> iteratorX = valueX.keys(); while (iteratorX.hasNext()) { String valueXkey = iteratorX.next(); String valueXValue = valueX.getString(valueXkey); String valueYValue = valueY.getString(valueXkey); dvalueX = Double.parseDouble(valueXValue); dvalueY = Double.parseDouble(valueYValue); } } catch (Exception e) { e.printStackTrace(); } } public void displayLocation(double dvalueX, double dvalueY) { Log.i("MainActivity", "进入displayLocation中"); LatLng latLng = new LatLng(dvalueY, dvalueX); //进行坐标转换 CoordinateConverter converter = new CoordinateConverter() .from(CoordinateConverter.CoordType.GPS) .coord(latLng); LatLng dLatlng = converter.convert(); //进行刷新时,先清除上一次的overlay baiduMap.clear(); //现添加Marker将位置在地图上标出来 BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.drawable.icon_niu32); OverlayOptions option = new MarkerOptions() .position(dLatlng) .icon(bitmap); baiduMap.addOverlay(option); } } ``` 方向传感器的监听类如下: ``` package com.example.gsontest; import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.util.Log; //方向监听器的类 public class MyOrientationListener implements SensorEventListener { private SensorManager mySensorManager; private Sensor mySensor; private Context myContext; private float lastX; private OnOrientationListener myOnOrientationListener; public void start(){ Log.i("MainActivity", "跳进了方向类的start函数中"); mySensorManager = (SensorManager) myContext.getSystemService(Context.SENSOR_SERVICE); if(mySensorManager!=null){ mySensor = mySensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION); } if(mySensor!=null){ //SENSOR_UI可能会出现数据滞后现象,若后期数据滞后则改成别的类型 mySensorManager.registerListener(this,mySensor,SensorManager.SENSOR_DELAY_NORMAL); } } //接触注册方向传感器监听事件,即对onDestroy中所引方法的实现 public void stop(){ Log.i("MainActivity","跳进方向类的stop函数中"); mySensorManager.unregisterListener(this); } //方向传感器的一个构造函数 public MyOrientationListener(Context myContext){ this.myContext = myContext; } @Override public void onAccuracyChanged(Sensor sensor,int accuracy){} //监听方向变化 @Override public void onSensorChanged(SensorEvent event){ Log.i("MainActivity","跳进了onSensorChanged函数中"); if(event.sensor.getType()==Sensor.TYPE_ORIENTATION){ float x = event.values[SensorManager.DATA_X]; if (Math.abs(x-lastX)>1.0){ if(myOnOrientationListener!=null){ myOnOrientationListener.onOrientationChanged(lastX); } } lastX = x; } } public void setOnOrientationListener(OnOrientationListener myOrientationListener){ this.myOnOrientationListener = myOrientationListener; } public interface OnOrientationListener{ void onOrientationChanged(float x); } } ``` 恳请大神帮忙看下程序谢谢!!

当响应只是表中的一行时,如何使用okhttp从json响应中获取java对象

<div class="post-text" itemprop="text"> <p>I'm trying to get a java object 'Product' from json response, the json response returns only one row from the table, and I don't khnow if I have to use a JSONObject or a JSONArray or both, anyway I've tried both but it doesn't work it's giving me a NullPointerException. Here'e my code: </p> <pre><code>public class ConsultProductActivity extends AppCompatActivity { String idProduit; Product prod; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); Bundle extra = intent.getExtras(); idProduit = extra.getString("idProduit"); Toast.makeText(ConsultProductActivity.this, idProduit, Toast.LENGTH_SHORT).show(); setContentView(R.layout.activity_consult_product); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_rest); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); prod = prepareFullInfo(); getSupportActionBar().setTitle(prod.getName()); ImageView imgAvant = (ImageView) findViewById(R.id.img_avant); Glide.with(ConsultProductActivity.this).load(prod.getImg_avant()).into(imgAvant); ImageView imgArriere = (ImageView) findViewById(R.id.img_arriere); Glide.with(ConsultProductActivity.this).load(prod.getImg_arriere()).into(imgArriere); ImageView imgCote = (ImageView) findViewById(R.id.img_cote); Glide.with(ConsultProductActivity.this).load(prod.getImg_coté()).into(imgCote); TextView prix = (TextView) findViewById(R.id.prix_consult_p); prix.setText(prod.getPrice()); AppCompatTextView description = (AppCompatTextView) findViewById(R.id.description); description.setText(prod.getDescription()); } public Product prepareFullInfo() { AsyncTask&lt;Void, Void, Void&gt; task = new AsyncTask&lt;Void, Void, Void&gt;() { String productUrl = new String("http://moodyinformatics.000webhostapp.com/product_full_info.php?id=" + idProduit); @Override protected Void doInBackground(Void... params) { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(productUrl).build(); try { Response response = client.newCall(request).execute(); JSONArray array = new JSONArray(response.body().string()); for (int i = 0; i &lt; array.length(); i++) { JSONObject object = array.getJSONObject(i); prod = new Product(object.getInt("id_produit"), object.getString("nom"), object.getString("description"), object.getInt("qte_stock"), object.getInt("prix"), object.getString("img_avant"), object.getString("img_arriere"), object.getString("img_cote")); } } catch (JSONException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void aVoid) { } }; task.execute(); return prod; } </code></pre> <p>My php file:</p> <pre><code>&lt;?php header('Content-Type: application/json; Charset=UTF-8'); require "conn.php"; $id_produit=$_GET['id']; $sql = "select p.id_produit, p.nom, p.description, p.prix, p.qte_stock, a.img_avant, a.img_arriere, a.img_cote from produit p, album_photos a where p.id_produit='".$id_produit."' and p.id_produit= a.id_produit"; $response = array(); $result = mysqli_query($conn, $sql); while ($row = mysqli_fetch_assoc($result)){ $array[]= $row; } $jsn= json_encode($array, JSON_UNESCAPED_UNICODE); $jsn1 = str_replace('\/', '/', $jsn); $jsn1 = str_replace(' ', ' ', $jsn1); $jsn1= str_replace('images/', 'http://moodyinformatics.000webhostapp.com/images/', $jsn1); echo $jsn1; mysqli_close($conn); ?&gt; </code></pre> <p>the response of the server when idProduit=12</p> <pre><code>[ { "id_produit":"12", "nom":"Switch Ethernet TP-Link TL-SG105", "description":"10/100/1000 : 5 ports Gigabit Contrôle de flux 802.3x : 802.3x Gestion QoS (Quality of Service) 802.1P : 802.1p", "prix":"3900", "qte_stock":"5", "img_avant":"http://moodyinformatics.000webhostapp.com/images/12.2.jpg", "img_arriere":"http://moodyinformatics.000webhostapp.com/images/12.3.jpg", "img_cote":"http://moodyinformatics.000webhostapp.com/images/12.4.jpg" } ] </code></pre> </div>

无法连接到000webhost上的PHP文件

<div class="post-text" itemprop="text"> <p>I got 1 app that is using retrofit2 to upload a picture to the 000webhost server and it works. Before that I used XAMPP to upload data to a database and now I am trying to move all of my work on XAMPP to 000webhost. The problem is that I get an error message when I try to upload data and the error is <code>could not invoke virtual method toString() on a null referance</code>. The java code is the same and the php files are the same ,except from the URL. I think there is a problem because the site is secured. Also using retrofit2 is difficult to me as I am having a hard time trying to understand how to use it but I can try with a good guide. Not Duplicate: I know what is a nullPoint Exception, the problem is that I do not understand why I receive a null value from the server. The app can't access the php file so it doesn't get a response and I do not understand how to fix it. Also why one app can access but the other can't.</p> <p>create_product.php:</p> <pre><code>&lt;?php $response = array(); if (isset($_POST['name']) &amp;&amp; isset($_POST['price']) &amp;&amp; isset($_POST['description'])) { $name = $_POST['name']; $price = $_POST['price']; $description = $_POST['description']; require_once __DIR__ . '/db_connect.php'; $db = new DB_CONNECT(); $result = $db-&gt;query("INSERT INTO products(name, price, description) VALUES('$name', '$price', '$description')"); if ($result) { $response["success"] = 1; $response["message"] = "Product successfully created."; echo json_encode($response); } else { $response["success"] = 0; $response["message"] = "Oops! An error occurred."; echo json_encode($response); } } else { $response["success"] = 0; $response["message"] = "missing fields"; echo json_encode($response); } ?&gt; </code></pre> <p>JSONParser:</p> <pre><code>package com.example.user.onlineshop; import android.content.ContentValues; import android.util.Log; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; public class JSONParser { static JSONObject jObj; static String json; // constructor public JSONParser() { } // function get json from url // by making HTTP POST or GET mehtod public static JSONObject makeHttpRequest(String url, String method, ContentValues params) { // Making HTTP request try { final OkHttpClient client = new OkHttpClient(); Request request; // check for request method if (method.equals("POST")) { // request method is POST MediaType contentType = MediaType.parse("application/x-www-form-urlencoded; charset=UTF-8"); String content = ""; for (String key : params.keySet()) { if ( !content.isEmpty()) content += "&amp;"; content += key + "=" + params.get(key); } RequestBody body = RequestBody.create(contentType, content); request = new Request.Builder().url(url).post(body).build(); } else { // request method is GET request = new Request.Builder().url(url).build(); } final Response response = client.newCall(request).execute(); json = response.body().string(); } catch (IOException e) { e.printStackTrace(); } // try parse the string to a JSON object try { jObj = new JSONObject(json); } catch (JSONException e ){ Log.e("JSON Parser", "Error parsing data " + e.toString()); } // return JSON String return jObj; } } </code></pre> <p>NewProductActivity:</p> <pre><code>package com.example.user.onlineshop; import android.app.Activity; import android.app.ProgressDialog; import android.content.ContentValues; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import org.json.JSONException; import org.json.JSONObject; public class NewProductActivity extends Activity { // Progress Dialog private ProgressDialog pDialog; JSONParser jsonParser = new JSONParser(); EditText inputName; EditText inputPrice; EditText inputDesc; ContentValues params; String name; String price; String description; // адрес для создания нового товара IpAddressClass IAC= new IpAddressClass(); String ip=IAC.getIp(); private String url_create_product = "http://swane2.000webhostapp.com/PicUpload/create_product.php"; // JSON Node names private static final String TAG_SUCCESS = "success"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_new_product); params = new ContentValues(); inputName = (EditText) findViewById(R.id.inputName); inputPrice = (EditText) findViewById(R.id.inputPrice); inputDesc = (EditText) findViewById(R.id.inputDesc); Button btnCreateProduct = (Button) findViewById(R.id.btnCreateProduct); btnCreateProduct.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // создаем новый товар в другом потоке name = inputName.getText().toString(); price = inputPrice.getText().toString(); description = inputDesc.getText().toString(); new CreateNewProductTask().execute(); } }); } // Фоновая задача для создания нового товара class CreateNewProductTask extends AsyncTask&lt;String, String, String&gt; { // Сначала запустим окно с индикатором прогресса @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(NewProductActivity.this); pDialog.setMessage("Creating product"); pDialog.setIndeterminate(false); pDialog.setCancelable(true); } // Создаем товар protected String doInBackground(String... args) { // Подготавливаем параметры params.put("name", name); params.put("price",price); params.put("description", description); // получаем объект JSON через POST JSONObject json = jsonParser.makeHttpRequest(url_create_product,"POST", params); Log.d("Create Response", json.toString()); // check for success tag try { int success = json.getInt(TAG_SUCCESS); if (success == 1) { // при успешном создании товара // запускаем активность всех товаров Intent i = new Intent(getApplicationContext(), AllProductsActivity.class); startActivity(i); // закрываем экран активности finish(); } else { // не получилось создать товар } } catch (JSONException e) { e.printStackTrace(); } return null; } protected void onPostExecute(String file_url) { // закрываем диалоговое окно с индикатором } } } </code></pre> <p>Edit: Before the error happens I get this message in the logcat:</p> <p><code>D/NetworkSecurityConfig: No Network Security Config specified, using platform default</code></p> </div>

在中国程序员是青春饭吗?

今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...

程序员请照顾好自己,周末病魔差点一套带走我。

程序员在一个周末的时间,得了重病,差点当场去世,还好及时挽救回来了。

Java基础知识面试题(2020最新版)

文章目录Java概述何为编程什么是Javajdk1.5之后的三大版本JVM、JRE和JDK的关系什么是跨平台性?原理是什么Java语言有哪些特点什么是字节码?采用字节码的最大好处是什么什么是Java程序的主类?应用程序和小程序的主类有何不同?Java应用程序与小程序之间有那些差别?Java和C++的区别Oracle JDK 和 OpenJDK 的对比基础语法数据类型Java有哪些数据类型switc...

技术大佬:我去,你写的 switch 语句也太老土了吧

昨天早上通过远程的方式 review 了两名新来同事的代码,大部分代码都写得很漂亮,严谨的同时注释也很到位,这令我非常满意。但当我看到他们当中有一个人写的 switch 语句时,还是忍不住破口大骂:“我擦,小王,你丫写的 switch 语句也太老土了吧!” 来看看小王写的代码吧,看完不要骂我装逼啊。 private static String createPlayer(PlayerTypes p...

和黑客斗争的 6 天!

互联网公司工作,很难避免不和黑客们打交道,我呆过的两家互联网公司,几乎每月每天每分钟都有黑客在公司网站上扫描。有的是寻找 Sql 注入的缺口,有的是寻找线上服务器可能存在的漏洞,大部分都...

Intellij IDEA 实用插件安利

1. 前言从2020 年 JVM 生态报告解读 可以看出Intellij IDEA 目前已经稳坐 Java IDE 头把交椅。而且统计得出付费用户已经超过了八成(国外统计)。IDEA 的...

女程序员,为什么比男程序员少???

昨天看到一档综艺节目,讨论了两个话题:(1)中国学生的数学成绩,平均下来看,会比国外好?为什么?(2)男生的数学成绩,平均下来看,会比女生好?为什么?同时,我又联想到了一个技术圈经常讨...

总结了 150 余个神奇网站,你不来瞅瞅吗?

原博客再更新,可能就没了,之后将持续更新本篇博客。

副业收入是我做程序媛的3倍,工作外的B面人生是怎样的?

提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...

MySQL数据库面试题(2020最新版)

文章目录数据库基础知识为什么要使用数据库什么是SQL?什么是MySQL?数据库三大范式是什么mysql有关权限的表都有哪几个MySQL的binlog有有几种录入格式?分别有什么区别?数据类型mysql有哪些数据类型引擎MySQL存储引擎MyISAM与InnoDB区别MyISAM索引与InnoDB索引的区别?InnoDB引擎的4大特性存储引擎选择索引什么是索引?索引有哪些优缺点?索引使用场景(重点)...

如果你是老板,你会不会踢了这样的员工?

有个好朋友ZS,是技术总监,昨天问我:“有一个老下属,跟了我很多年,做事勤勤恳恳,主动性也很好。但随着公司的发展,他的进步速度,跟不上团队的步伐了,有点...

我入职阿里后,才知道原来简历这么写

私下里,有不少读者问我:“二哥,如何才能写出一份专业的技术简历呢?我总感觉自己写的简历太烂了,所以投了无数份,都石沉大海了。”说实话,我自己好多年没有写过简历了,但我认识的一个同行,他在阿里,给我说了一些他当年写简历的方法论,我感觉太牛逼了,实在是忍不住,就分享了出来,希望能够帮助到你。 01、简历的本质 作为简历的撰写者,你必须要搞清楚一点,简历的本质是什么,它就是为了来销售你的价值主张的。往深...

魂迁光刻,梦绕芯片,中芯国际终获ASML大型光刻机

据羊城晚报报道,近日中芯国际从荷兰进口的一台大型光刻机,顺利通过深圳出口加工区场站两道闸口进入厂区,中芯国际发表公告称该光刻机并非此前盛传的EUV光刻机,主要用于企业复工复产后的生产线扩容。 我们知道EUV主要用于7nm及以下制程的芯片制造,光刻机作为集成电路制造中最关键的设备,对芯片制作工艺有着决定性的影响,被誉为“超精密制造技术皇冠上的明珠”,根据之前中芯国际的公报,目...

优雅的替换if-else语句

场景 日常开发,if-else语句写的不少吧??当逻辑分支非常多的时候,if-else套了一层又一层,虽然业务功能倒是实现了,但是看起来是真的很不优雅,尤其是对于我这种有强迫症的程序"猿",看到这么多if-else,脑袋瓜子就嗡嗡的,总想着解锁新姿势:干掉过多的if-else!!!本文将介绍三板斧手段: 优先判断条件,条件不满足的,逻辑及时中断返回; 采用策略模式+工厂模式; 结合注解,锦...

离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...

2020阿里全球数学大赛:3万名高手、4道题、2天2夜未交卷

阿里巴巴全球数学竞赛( Alibaba Global Mathematics Competition)由马云发起,由中国科学技术协会、阿里巴巴基金会、阿里巴巴达摩院共同举办。大赛不设报名门槛,全世界爱好数学的人都可参与,不论是否出身数学专业、是否投身数学研究。 2020年阿里巴巴达摩院邀请北京大学、剑桥大学、浙江大学等高校的顶尖数学教师组建了出题组。中科院院士、美国艺术与科学院院士、北京国际数学...

为什么你不想学习?只想玩?人是如何一步一步废掉的

不知道是不是只有我这样子,还是你们也有过类似的经历。 上学的时候总有很多光辉历史,学年名列前茅,或者单科目大佬,但是虽然慢慢地长大了,你开始懈怠了,开始废掉了。。。 什么?你说不知道具体的情况是怎么样的? 我来告诉你: 你常常潜意识里或者心理觉得,自己真正的生活或者奋斗还没有开始。总是幻想着自己还拥有大把时间,还有无限的可能,自己还能逆风翻盘,只不是自己还没开始罢了,自己以后肯定会变得特别厉害...

男生更看重女生的身材脸蛋,还是思想?

往往,我们看不进去大段大段的逻辑。深刻的哲理,往往短而精悍,一阵见血。问:产品经理挺漂亮的,有点心动,但不知道合不合得来。男生更看重女生的身材脸蛋,还是...

为什么程序员做外包会被瞧不起?

二哥,有个事想询问下您的意见,您觉得应届生值得去外包吗?公司虽然挺大的,中xx,但待遇感觉挺低,马上要报到,挺纠结的。

当HR压你价,说你只值7K,你该怎么回答?

当HR压你价,说你只值7K时,你可以流畅地回答,记住,是流畅,不能犹豫。 礼貌地说:“7K是吗?了解了。嗯~其实我对贵司的面试官印象很好。只不过,现在我的手头上已经有一份11K的offer。来面试,主要也是自己对贵司挺有兴趣的,所以过来看看……”(未完) 这段话主要是陪HR互诈的同时,从公司兴趣,公司职员印象上,都给予对方正面的肯定,既能提升HR的好感度,又能让谈判气氛融洽,为后面的发挥留足空间。...

面试:第十六章:Java中级开发

HashMap底层实现原理,红黑树,B+树,B树的结构原理 Spring的AOP和IOC是什么?它们常见的使用场景有哪些?Spring事务,事务的属性,传播行为,数据库隔离级别 Spring和SpringMVC,MyBatis以及SpringBoot的注解分别有哪些?SpringMVC的工作原理,SpringBoot框架的优点,MyBatis框架的优点 SpringCould组件有哪些,他们...

面试阿里p7,被按在地上摩擦,鬼知道我经历了什么?

面试阿里p7被问到的问题(当时我只知道第一个):@Conditional是做什么的?@Conditional多个条件是什么逻辑关系?条件判断在什么时候执...

Python爬虫,高清美图我全都要(彼岸桌面壁纸)

爬取彼岸桌面网站较为简单,用到了requests、lxml、Beautiful Soup4

差点跪了...

最近微信又搞出了一个大利器,甚至都上了热搜,当然消息最敏捷的自媒体人,纷纷都开通了自己的视频号。01 视频号是什么呢?视频号是微信体系内的短视频,它不同...

面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?

最近面试了一个31岁8年经验的程序猿,让我有点感慨,大龄程序猿该何去何从。

Vue回炉重造之router路由(更新中)

你好,我是Vam的金豆之路,可以叫我豆哥。2019年年度博客之星、技术领域博客专家。主要领域:前端开发。我的微信是 maomin9761,有什么疑问可以加我哦,自己创建了一个微信技术交流群,可以加我邀请你一起交流学习。最后自己也创建了一个微信公众号,里面的文章是我自己精挑细选的文章,主要介绍各种IT新技术。欢迎关注哦,微信搜索:臻美IT,等你来。 欢迎阅读本博文,本博文主要讲述【】,文字通...

大三实习生,字节跳动面经分享,已拿Offer

说实话,自己的算法,我一个不会,太难了吧

程序员垃圾简历长什么样?

已经连续五年参加大厂校招、社招的技术面试工作,简历看的不下于万份 这篇文章会用实例告诉你,什么是差的程序员简历! 疫情快要结束了,各个公司也都开始春招了,作为即将红遍大江南北的新晋UP主,那当然要为小伙伴们做点事(手动狗头)。 就在公众号里公开征简历,义务帮大家看,并一一点评。《启舰:春招在即,义务帮大家看看简历吧》 一石激起千层浪,三天收到两百多封简历。 花光了两个星期的所有空闲时...

Java岗开发3年,公司临时抽查算法,离职后这几题我记一辈子

前几天我们公司做了一件蠢事,非常非常愚蠢的事情。我原以为从学校出来之后,除了找工作有测试外,不会有任何与考试有关的事儿。 但是,天有不测风云,公司技术总监、人事总监两位大佬突然降临到我们事业线,叫上我老大,给我们组织了一场别开生面的“考试”。 那是一个风和日丽的下午,我翘着二郎腿,左手端着一杯卡布奇诺,右手抓着我的罗技鼠标,滚动着轮轴,穿梭在头条热点之间。 “淡黄的长裙~蓬松的头发...

大胆预测下未来5年的Web开发

在2019年的ReactiveConf 上,《Elm in Action》的作者Richard Feldman对未来5年Web开发的发展做了预测,很有意思,分享给大家。如果你有机会从头...

大牛都会用的IDEA调试技巧!!!

导读 前天面试了一个985高校的实习生,问了他平时用什么开发工具,他想也没想的说IDEA,于是我抛砖引玉的问了一下IDEA的调试用过吧,你说说怎么设置断点...

都前后端分离了,咱就别做页面跳转了!统统 JSON 交互

文章目录1. 无状态登录1.1 什么是有状态1.2 什么是无状态1.3 如何实现无状态1.4 各自优缺点2. 登录交互2.1 前后端分离的数据交互2.2 登录成功2.3 登录失败3. 未认证处理方案4. 注销登录 这是本系列的第四篇,有小伙伴找不到之前文章,松哥给大家列一个索引出来: 挖一个大坑,Spring Security 开搞! 松哥手把手带你入门 Spring Security,别再问密...

面试官:你连SSO都不懂,就别来面试了

大厂竟然要考我SSO,卧槽。

实时更新:计算机编程语言排行榜—TIOBE世界编程语言排行榜(2020年6月份最新版)

内容导航: 1、TIOBE排行榜 2、总榜(2020年6月份) 3、本月前三名 3.1、C 3.2、Java 3.3、Python 4、学习路线图 5、参考地址 1、TIOBE排行榜 TIOBE排行榜是根据全世界互联网上有经验的程序员、课程和第三方厂商的数量,并使用搜索引擎(如Google、Bing、Yahoo!)以及Wikipedia、Amazon、YouTube统计出排名数据。

终于,月薪过5万了!

来看几个问题想不想月薪超过5万?想不想进入公司架构组?想不想成为项目组的负责人?想不想成为spring的高手,超越99%的对手?那么本文内容是你必须要掌握的。本文主要详解bean的生命...

​能让德国人放弃现金支付​,也没谁了

在新冠疫情中,德国人越来越多地选择在超市,加油站或其他商店付款时使用非接触式付款方式。德国信贷协会Deutschen Kreditwirtschaft (DK) 的一位发言人告诉德国新...

立即提问
相关内容推荐