android通过post方式传值给javaweb,数据一直传送不成功

sdssb 2017-09-04 04:55:14
我按照网上的资源写的代码,通过POST传一个name的值,但服务器端一直没有接收到
下面是android客户端的代码

package activitytest.example.com.fangzhongapp;

import android.app.DownloadManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
TextView responseText;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button chaxun=(Button)findViewById(R.id.chaxun);
responseText=(TextView)findViewById(R.id.response_text);
chaxun.setOnClickListener(this);

}
public void onClick(View v){
if(v.getId()==R.id.chaxun){
fasongPost("xiaohong");
// try {
// Thread thr=new Thread(MainActivity.class);
// thr.currentThread().sleep(2000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
send();
}
}
private void fasongPost(final String str){
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection=null;
OutputStream out=null;
try {
URL url=new URL("http://10.0.2.2:8080/ServerDuan/utilServer.action");
connection=(HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestProperty("Content-Type","application/x-www-from-urlencoded");
connection.setRequestProperty("Charset","utf-8");
String data="name="+ URLEncoder.encode(str,"UTF-8");
connection.setRequestProperty("Content-Length",String.valueOf(data.getBytes().length));
out=connection.getOutputStream();
// out.writeBytes("name="+str);
// connection.setInstanceFollowRedirects(true);
// String data="name="+str;
connection.connect();
out.write(data.getBytes(),0,data.getBytes().length);
out.flush();
int requestCode=connection.getResponseCode();
Log.d("MainActivity",""+requestCode);
} catch (IOException e) {
e.printStackTrace();
}finally{
// if(out!=null){
// try {
// out.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
connection.disconnect();

}

}
}).start();
}
private void send(){
new Thread(new Runnable() {
@Override
public void run() {
try {
OkHttpClient client=new OkHttpClient();
Request request=new Request.Builder()
.url("http://10.0.2.2:8080/ServerDuan/json/android.json")
.build();
Response response=client.newCall(request).execute();
String responseData=response.body().string();
parseJSONWithJSONObject(responseData);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
private void showResponse(final String response){
runOnUiThread(new Runnable() {
@Override
public void run() {
responseText.setText(response);
}
});
}
private void parseJSONWithJSONObject(String jsonData){
Gson gson =new Gson();
String str="";
try {
List<Util> appList=gson.fromJson(jsonData, new TypeToken<List<Util>>(){}.getType());

for(Util util:appList){
str=str+""+util.toString();
}
} catch (JsonSyntaxException e) {
e.printStackTrace();
Util util=gson.fromJson(jsonData,Util.class);
str=util.toString();
}

showResponse(str);
}
}


这是服务器端的代码
package com.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;

@WebServlet("/utilServer.action")
public class UtilServer extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
super.doGet(req, resp);
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
req.setCharacterEncoding("utf-8");
String name=req.getParameter("name");
System.out.println(name);

UtilDao dao=new UtilDao();
Utils util=dao.findBy(name);

// String str="[{\"id\":\""+util.getId()+"\",\"name\":\""+util.getName()+"\",\"addr\":\""+util.getAddr()+"\"}]";
String jsonString=JSON.toJSONString(util);
String fullPath=req.getSession().getServletContext().getRealPath("/")+"json\\android.json";
// System.out.println(Thread.currentThread().getContextClassLoader().getResource("").getPath());
// System.out.println(req.getSession().getServletContext().getRealPath("/"));
System.out.println(req.getServletPath());
File file=new File(fullPath);
if(!file.getParentFile().exists()){
file.getParentFile().mkdirs();
}
if(file.exists()){
file.delete();
}
file.createNewFile();
Writer write=new OutputStreamWriter(new FileOutputStream(file),"UTF-8");
write.write(jsonString);
write.flush();
write.close();
}

}
...全文
551 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
AndroidDev2022 2017-09-30
  • 打赏
  • 举报
回复
看看我写的这个 http://blog.csdn.net/jdfkldjlkjdl/article/details/76502229
风龙-3 2017-09-28
  • 打赏
  • 举报
回复
整个来看,你是post一个名字到服务端,然后服务端将名字存储到json文件中,最后你再从服务端获取这个文件; 从整体上看,时间没这么快;也就是你服务端可能在存的时候,客户端就要去取文件了,这时候还没有;
一个小狼娃 2017-09-28
  • 打赏
  • 举报
回复
你可以试一试RXJava+Retrofit
Jing丶無雙 2017-09-27
  • 打赏
  • 举报
回复
你这是在用OkHttp3吧,去看看这个例子http://download.csdn.net/download/xj396282771/9884999
sdssb 2017-09-25
  • 打赏
  • 举报
回复
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="#006600"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=""
            android:textSize="22sp"
            android:textColor="#FFFFFF"/>
    </android.support.v7.widget.Toolbar>
    <ScrollView
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/toolbar">
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <RelativeLayout
                android:id="@+id/relative"
                android:layout_width="match_parent"
                android:layout_height="150dp"
                android:background="#66cc66">
                <TextView
                    android:layout_width="210dp"
                    android:layout_height="wrap_content"
                    android:background="@drawable/shape2"
                    android:text="移动端应用"
                    android:textSize="30sp"
                    android:textColor="#FFFFFF"
                    android:gravity="center_horizontal"
                    android:layout_centerInParent="true"/>
            </RelativeLayout>
            <LinearLayout
                android:id="@+id/linear1"
                android:layout_below="@id/relative"
                android:orientation="horizontal"
                android:layout_width="match_parent"
                android:layout_height="60dp">
                <TextView
                    android:layout_width="90dp"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_vertical"
                    android:textSize="18sp"
                    android:text="用户名"/>
                <EditText
                    android:id="@+id/account"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:layout_gravity="center_vertical"/>
            </LinearLayout>
            <LinearLayout
                android:id="@+id/linear2"
                android:layout_below="@id/linear1"
                android:orientation="horizontal"
                android:layout_width="match_parent"
                android:layout_height="60dp">
                <TextView
                    android:layout_width="90dp"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_vertical"
                    android:textSize="18sp"
                    android:text="密码"/>
                <EditText
                    android:id="@+id/password"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:layout_gravity="center_vertical"
                    android:inputType="textPassword"/>
            </LinearLayout>
            <LinearLayout
                android:id="@+id/linear3"
                android:layout_below="@id/linear2"
                android:orientation="horizontal"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
                <CheckBox
                    android:id="@+id/remember_pass"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="18sp"
                    android:text="记住密码"/>
                <CheckBox
                    android:id="@+id/zddl"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="自动登录"
                    android:textSize="18sp"/>
            </LinearLayout>
            <LinearLayout
                android:id="@+id/linear4"
                android:layout_below="@id/linear3"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:weightSum="1">
                <Button
                    android:id="@+id/login"
                    android:layout_width="0dp"
                    android:layout_height="60dp"
                    android:layout_weight="0.8"
                    android:background="@drawable/shape"
                    android:text="登录"
                    android:textSize="22sp"
                    android:textColor="@android:color/background_light" />
            </LinearLayout>

        </RelativeLayout>

    </ScrollView>
    <RelativeLayout
        android:layout_alignParentBottom="true"
        android:layout_width="match_parent"
        android:layout_height="26dp"
        android:background="#006600">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=""
            android:textColor="#ffffff"
            android:layout_centerInParent="true"/>
    </RelativeLayout>


</RelativeLayout>

80,337

社区成员

发帖
与我相关
我的任务
社区描述
移动平台 Android
androidandroid-studioandroidx 技术论坛(原bbs)
社区管理员
  • Android
  • yechaoa
  • 失落夏天
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧